【问题标题】:Mongoose retrieving data without _id fieldMongoose 检索没有 _id 字段的数据
【发布时间】:2012-03-24 19:19:43
【问题描述】:

我想从我的 Node.js 应用程序中的 Mongoose 设置中检索一些数据。我注意到无论我写什么作为字段选择,我总是得到_id 字段。有办法不取吗? 这就是我现在的做法:

Transaction.find({username : user.username}, ['uniqueId', 'timeout', 'confirmation_link', 'item_name'], function(err, txs){
        console.log("user : " + user.username + " with txs: " + txs);
        callback(txs);
});

并记录包含_id 字段的结果。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    另一种方法是使用带有前缀- 的文本参数,这将从结果中排除这个或那个字段:

    Entity.find({ ... }, '-_id field1 field2', function(err, entity) {
        console.log(entity);  // { field1: '...', field2: '...' }
    });
    

    【讨论】:

    • 这似乎是更优雅的语法。
    • 是的,比第一个好多了。好一个@VisioN
    • 更优雅! +1
    • 太棒了。我还注意到,如果您使用“-_id”,Mongoose 将返回除 _id 之外的所有字段。太棒了。
    • 太棒了!我像这样使用它: const publicUserValues = ['-_id', 'name', 'website', 'bio']; const user = await User.findOne({ username }, publicUserValues).exec();
    【解决方案2】:

    _id 必须明确排除。例如,

    Transaction.find({username : user.username}, { '_id': 0, 'uniqueId' :1, 'timeout': 1, 'confirmation_link': 1, 'item_name': 1}, function(err, txs){
      console.log("user : " + user.username + " with txs: " + txs);
      callback(txs);
    });
    

    【讨论】:

    • 你能排除_id并且仍然保留id吗?我注意到 id 是一个虚拟字段。我想要 id 但在我的 REST api 中排除 _id 。现在,当我排除 _id 时,id 变为 null
    • 我们也可以排除嵌套的_id(例如:cars._id: 0)
    • 如何在子文档中排除_id,上面的命令将其从外部文档中排除,但不从子文档中排除。
    • @jazeb007 Transaction.find({}).select("-_id").populate({path:"product",select:"-_id"}) 这应该排除 '_id'文档和子文档。
    【解决方案3】:

    另一种方法:

    • 增加架构的 .toJSON() 以删除 _id__v 字段
    • 对发送给客户端的所有数据库对象调用.toJSON()
    • 额外好处#1:您可以使用item.id === 'something',因为typeof id === 'string',而不是ObjectId
    • 额外好处 #2:当您从客户端取回 gan 对象并且想要搜索/更新时,您不必手动删除 _id,因为没有,只有 id 被忽略。

    增强 JSON:

    mySchema.set('toJSON', {
        virtuals: true,
        transform: (doc, ret, options) => {
            delete ret.__v;
            ret.id = ret._id.toString();
            delete ret._id;
        },
    });
    

    所以你可以使用:

     let item = (await MyCollection.findOne({/* search */}).exec()).toJSON();
     if (item.id === 'someString') return item;
    

    我知道这很丑。但这是我迄今为止最好的坏主意。

    【讨论】:

      【解决方案4】:

      在 5.2.13 版本的 Mongoose(2018 年 9 月)中 - 使用查询构建器方法同样可以转换为

      async function getUserDetails(user) {
          try {
              if (!user || !user.name) return;
              const result = await Transaction.
              find({username : user.username}).
              select('uniqueId timeout confirmation_link item_name -_id'); 
              // Adding minus sign before the _id (like -_id) in the select string unselects the _id which is sent by default. 
              console.log(result);
          } catch(ex) {
              return ex
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-09
        • 2012-10-10
        • 2015-03-25
        • 2015-03-31
        • 1970-01-01
        • 2021-10-04
        • 2018-07-22
        相关资源
        最近更新 更多