mongoose.connection
返回本地MongoDB连接,您使用该连接执行的所有操作
db.
前缀和直接在MongoDB控制台上执行的相同。
所以在使用本机连接描述符时,不要等待Mongoose执行相同的操作。
当您以本地方式处理集合时,您必须理解
find
方法返回光标。
const db = mongoose.connection.db;
const collections = db.listCollections()
collections
.toArray((error, collections) => {
collections.foreach(async collection => {
const query = {"duck_name": { $exists: true }};
const count = await collection.find(query).count();
if (count === 0) return;
console.log('Found:', count, 'documents in collection:', collection.name);
const cursor = await collection.find(query);
while(await cursor.hasNext()) {
const document = await cursor.next();
console.log('document:', document._id);
}
})
});
或使用
toArray
光标上的方法:
const db = mongoose.connection.db;
const collections = db.listCollections()
collections
.toArray((error, collections) => {
collections.foreach(async collection => {
const query = {"duck_name": { $exists: true }};
const count = await collection.find(query).count();
if (count === 0) return;
console.log('Found:', count, 'documents in collection:', collection.name);
const documents = await collection.find(query).toArray();
for(const document of documents) {
console.log('document:', document._id);
}
})
});