这是我的代码,用于从使用集合名称初始化的集合组名中获取数据。我想使用 foreach
循环迭代存储在 doc 中的数据。
var db = mongojs('login');
var cursor = db.collection(groupname).find();
console.log(cursor);
cursor.each(function(err, doc) {
console.log(doc._id);
mongo.collection(doc._id + "group", function(err, collection) {
collection.remove({"groupname": groupname});
});
});
我试过执行 db.collectionname.find().forEach(....)
,但我收到一条错误消息,指出此类函数不存在。请帮忙。
最佳答案
从 Mongo DB 获取记录的 find()
调用是异步的。您甚至在数据可用之前就尝试使用文档。你应该在 find()
的回调中有你的 forEach
循环。
`
db.collection(groupname).find({}, function(err, doc){
console.log(doc);
doc.forEach(function(err,doc){
console.log(doc._id);
db=mongo.collection(doc_id+"group");
db.remove({"groupname":groupname});
});
});
`
关于node.js - 如何在nodejs中使用foreach进行Mongodb操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33542006/