Mongoose在没有_id字段的情况下检索数据

Mas*_*iar 45 mongoose node.js

我想从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);
});
Run Code Online (Sandbox Code Playgroud)

并记录包含该_id字段的结果.

Vis*_*ioN 87

另一种方法是使用带有前缀的text参数,-该参数将从结果中排除此字段或该字段:

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

  • 这似乎是更优雅的语法. (2认同)

dan*_*ugh 57

_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);
});
Run Code Online (Sandbox Code Playgroud)

  • 你可以排除_id并仍然保持id吗?我注意到id是一个虚拟字段.我想拥有id但在我的REST api中排除_id.现在,当我排除_id时,id变为null (3认同)
  • 如何在子文档中排除 _id,上面的命令将其从外部文档中排除,但不从子文档中排除。 (3认同)

Gáb*_*mre 13

另一种方法:

  • 扩充 .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;
    },
});
Run Code Online (Sandbox Code Playgroud)

所以你可以使用:

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

我知道这很难看.但到目前为止,这是我最好的坏主意.


Dur*_*rai 8

在 Mongoose 的 5.2.13 版本(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
    }
}
Run Code Online (Sandbox Code Playgroud)