如何在nodejs中使用foreach来执行Mongodb操作
这是我的代码从集合名称获取集合名称的集合名称。 我想用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(....)
,但我有一个错误,说这样的function不存在。 请帮忙。
从MongoDB中获取logging的find()
调用是asynchronous的。 甚至在数据可用之前,您正在尝试使用这些文档。 您应该在find()
callbackforEach
中拥有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}); }); });
`
使用each()
方法遍历find()
游标的所有文档:
// Grab a cursor var cursor = db.collection(groupname).find(); console.log(cursor); // Execute the each command, triggers for each document cursor.each(function(err, doc) { console.log(doc._id); // Fetch a collection to remove document mongo.collection(doc._id + "group", function(err, collection) { collection.remove({"groupname": groupname}); } });
– 更新 –
在编辑之后发现你正在使用mongojs库,你需要传递一个callback函数来处理查询的结果,因为Node.js实现了一个asynchronous范例,而且几乎所有东西都是一个callback,它允许你的应用程序是非阻塞的和高性能:
// connect now, and worry about collections later var db = mongojs('login') var groupcollection = db.collection(groupname) groupcollection.find({}, function(err, groups) { if( err || !groups) console.log("No groups found"); else groups.forEach( function(group) { console.log(group); mongo.collection(group._id + "group", function(err, collection) { collection.remove({"groupname": groupname}); }); }); });