【发布时间】:2016-08-23 21:31:09
【问题描述】:
在 node.js 中,我正在编写将文档插入集合的查询,但该查询仅插入一个文档。下面是js代码,
app.js
router.post('/creatList', function(req,res){
console.log(req.body.email);
var emails = req.body.email;
if(req.body.wData.wishListType == 'Shared'){
var findUsers = function(db, callback) {
var cursor;
cursor = db.collection('users').find({email: { $in: emails }})
cursor.toArray(function(err, docs){
if(err){
callback(new Error("Some problem"));
} else {
callback(null,docs);
}
});
};
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
findUsers(db, function(err,docs) {
db.close();
console.log(docs);
var inserts_processing = 0;
for(var key in docs){
console.log(key);
var ids = docs[key]._id;
inserts_processing++;
console.log(ids);
var insertDocument = function(db, callback) {
db.collection('notifications').insertOne({
"userId" : ids,
},function(err, result) {
inserts_processing--;
assert.equal(err, null);
console.log("Inserted a document into the notifications collection.");
if(inserts_processing == 0){
db.close();
callback();
}
});
};
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
}
});
});
} else {
console.log("other");
}
});
在上面的代码中,console.log 包含两个 ids 570dec75cf30bf4c09679deb
56fe44836ce2226431f5388f 但实际上它只插入了最后一个。
【问题讨论】:
-
您的路线没有任何响应?而且我不明白为什么您每次需要时都打开/关闭 MongoDB 连接。
-
没有路线工作正常