一个网页通过POST将JSON数据发送到我的Node.js应用程序(使用Mongoose的MEAN环境)。JSON文件如下所示(摘录):
Firstname: 'XY',
Surname: 'asd',
Articles:
[ { title: '1', description: 'XY' },
{ title: '2', description: 'XY' },
{ title: '3', description: 'XY' }
目的是在mongodb数据库中创建作者,将作者添加到其他目录,存储相关文章,并在作者文档中创建对这些文章的引用(不包括代码)。这是处理请求的代码:
[...]
async.waterfall([
//Create random code for author (besides mongodb-specific id)
function(callback){
newAuthorCode.randomAuthorCode(function(err, code) {
callback(null, code);
});
},
//Save new author to db
function(code, callback){
var newAuthor = new Author({firstname: req.body.Firstname,
surname: req.body.Surname,
identcode: code
});
newAuthor.save(function (err){
callback(null, newAuthor);
});
},
//Add new author to an additional directory
function(newAuthor, callback){
Directory.update({_id: req.user._id}, {$push: {authorids: newAuthor._id }}, function(err, update){
if (update){
callback(null);
}
});
},
//saves articles to db
function(callback){
var keys = Object.keys(req.body.articles);
for(var i=0, length=keys.length; i<length; i++){
var newArticle = new Article({title: req.body.Articles[keys[i]].title,
description: req.body.Articles[keys[i]].description
});
newArticle.save(function (err){
console.log(newArticle._id); // <--- !!!!!!!
});
}
callback(null);
}
], function (err, result) {
console.log('DONE!!!');
res.send('200');
});
我的问题:
1)我尝试输出生成的文章的所有ID的标记代码行仅传递i乘以存储的最后一篇文章的ID(在此情况下为第3条)。
2)问题1导致我无法在作者文档(存储在另一个收藏集中)中创建新创建文章的引用,因为我只能访问最后一个ID,因此无法访问!
3)有时作者和文章在数据库中创建了多次(两者之间有巨大的时间间隔)!
感谢您提出的任何建议,因为我没有足够的想法了。
伊戈尔
不确定newLink
代码中包含什么,但是您可以尝试以下方法:
newArticle.save(function (err, newDoc){
console.log(newDoc._id); // <--- !!!!!!!
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句