【问题标题】:Mongo Find() function won't exclude _idMongo Find() 函数不会排除 _id
【发布时间】:2021-04-03 05:57:43
【问题描述】:

您好,我似乎无法让排除 _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);
  });
}

这是控制台日志的输出

Found the following records
[ { _id: 5a5ee78cc130e727a3b1fdb6, name: 'Downgradeklajds' },
  { _id: 5a5ee794c130e727a3b1fdb7, Pizel: '00:00:07' } ]

我哪里做错了?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    我认为指定投影的正确方法是使用“字段”或“投影”属性,具体取决于驱动程序的版本。

    collection.find({}, {projection:{ _id: 0 }})
    

    阅读文档here。

    【讨论】:

    • 你太棒了,解决方案奏效了!我希望你有一个美好的一天,并在地板上找到一张幸运的 20 美元钞票!
    • @Lee,你也为我节省了数小时的挫败感。谢谢!!
    • @user1791914 很高兴它有帮助。
    • 对于任何使用 pymongo 的人,请使用:collection.find({}, {'_id': False})
    【解决方案2】:

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

    collection.find({}, {_id: 0 })  
    

    其中 find {} 指的是所有(无限制),下一个参数是投影,因此 0 或 False 不包括 _id(与 {_id: False } 相同)

    【讨论】:

      【解决方案3】:

      如果你使用findOne,

      你可以试试

          const posts : Collection= db.collection('posts')
          let document = await posts.findOne({
                  path: path
              }, {
                  fields: {
                      _id: 0
              }
          })
      

      例如,我查询路径(用作_id)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 2022-11-04
        • 2018-11-27
        • 2017-04-15
        相关资源
        最近更新 更多