Mongo Find()函数不会排除_id

Ric*_*cky 3 mongodb

你好我似乎无法让exclude _id工作,这是代码

const findLabels = (db, cb) => {
  // Get the documents collection
  const collection = db.collection(documentName);

  // Find some documents
  collection.find({}, { _id: 0 }).toArray((err, docs) => {
    // An error occurred we need to return that to the given 
    // callback function
    if (err) {
      return cb(err);
    }

    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs)

    return cb(null, docs);
  });
}
Run Code Online (Sandbox Code Playgroud)

这是控制台日志中的输出

Found the following records
[ { _id: 5a5ee78cc130e727a3b1fdb6, name: 'Downgradeklajds' },
  { _id: 5a5ee794c130e727a3b1fdb7, Pizel: '00:00:07' } ]
Run Code Online (Sandbox Code Playgroud)

我哪里做错了?

Lee*_*Lee 15

我认为指定投影的正确方法是使用"fields"或"projection"属性,具体取决于驱动程序的版本.

collection.find({}, {projection:{ _id: 0 }})
Run Code Online (Sandbox Code Playgroud)

阅读文档这里.

  • 你太棒了,解决方案有效!希望您度过愉快的一天,并在地板上找到一张幸运的 20 美元钞票! (2认同)

adh*_*dhg 10

对于新版本只需执行以下操作:

collection.find({}, {_id: 0 })  
Run Code Online (Sandbox Code Playgroud)

其中 find {} 指的是全部(无限制),下一个参数是投影,因此 0 或 False 排除 _id(与 相同{_id: False }