これはコレクションの名前で初期化されたコレクションgroupnameからデータを取得するための私のコードです。私はを使用してdocに格納されているデータを繰り返したい foreach
ループ。
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(....)
しかし、そのような関数が存在しないというエラーが出ました。助けてください。
回答:
回答№1は4ザ find()
Mongo DBからレコードを取得するための呼び出しは非同期です。データが入手可能になる前であっても、ドキュメントを使用しようとしています。あなたはあなたがいるべきです forEach
のコールバックのループ find()
.
`
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});
});
});
`
回答№2については2
使用 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 あなたの編集後のライブラリは、あなたが渡す必要がありますNode.jsが非同期パラダイムを実装しているため、クエリの結果を処理するコールバック関数があり、ほとんどすべてがコールバックであり、アプリはノンブロッキングで高性能です。
// 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});
});
});
});