【发布时间】:2014-11-22 16:14:17
【问题描述】:
网页通过 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 的标记代码行仅提供最后存储的文章 ID 的 i 倍(在本例中为文章 3)。
2) 问题 1 导致我无法在作者文档(存储在不同的集合中)中创建新创建文章的引用,因为除了最后一个,我无法访问任何文章 ID!?
3) 有时作者和文章会在数据库中多次创建(两者之间有巨大的时间间隔)!?
感谢您的任何建议,因为我的想法已经不多了。
伊戈尔
【问题讨论】:
标签: javascript node.js mongodb mongoose