使用节点js的Mongo文档的文档ID

以下是检索集合中所有文档的代码。

db.collection('movies', function(err, collectionref) { // find all documents in a collection that have foo: "bar" var cursor = collectionref.find({}); cursor.toArray(function(err, docs) { // gets executed once all items are retrieved res.render('movie', {'movies': docs}); }); }); 

我想要使​​用节点js收集所有文档的id。

你可以迭代游标对象来得到这样的_id:

 var cursor = db.inventory.find( {} ); while (cursor.hasNext()) { console.log(tojson(cursor.next())._id); } 

幸运的是,因为它只是JavaScript,所以提供了正常的集合迭代器:

 // find all documents that are "movies" db.movies.find({}) .map(function(doc) { // iterate and return only the _id field for each document return doc._id; }); 

比较正式的MongoDB-ish名字是cursor.map ,它是:

对由游标访问的每个文档应用函数,并将来自连续应用程序的返回值收集到数组中。

我提供的链接中的文档中的例子也很清楚:

 db.users.find().map( function(u) { return u.name; } ); 

这个function在很多方面模仿了原生的Array.prototype.map (如果你不熟悉这个方法,我会build议阅读这些文档)。