Node.js Mongoose正在检索没有_id字段的数据

Node.js Mongoose正在检索没有_id字段的数据,node.js,mongoose,Node.js,Mongoose,我想从Node.js应用程序中的Mongoose设置中检索一些数据。我注意到,无论我写什么作为字段选择,我总是得到\u id字段。有办法不去拿吗? 我现在就是这样做的: Transaction.find({username : user.username}, ['uniqueId', 'timeout', 'confirmation_link', 'item_name'], function(err, txs){ console.log("user : " + user.user

我想从Node.js应用程序中的Mongoose设置中检索一些数据。我注意到,无论我写什么作为字段选择,我总是得到
\u 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);
});

并记录包含
\u id
字段的结果。

\u 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);
});

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

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

  • 增加模式的
    .toJSON()
    ,删除
    \u id
    \u v
    字段
  • 对发送到客户端的所有DB对象调用
    .toJSON()
  • 额外好处1:您可以使用
    item.id==='something'
    ,因为
    typeof id=='string'
    ,而不是
    ObjectId
  • 额外好处#2:当您从客户端获得一个对象并希望搜索/更新时,您不必手动删除
    \u 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;

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

在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
    }
}

这似乎是更优雅的语法。是的,比第一个好得多。好的@Vision更优雅+1我们很好。我还注意到,如果使用“-u id”,Mongoose将返回除_id.mavelous.excellel之外的所有字段!我像这样使用它:constpublicUserValues=['-\u id',name',website',bio'];const user=wait user.findOne({username},publicUserValues.exec();你能排除_id并保留id吗?我注意到id是一个虚拟字段。我希望在REST api中有id,但不包括_id。现在,当我排除_id时,id变为空。我们还可以排除嵌套的_id(例如cars._id:0)。如何排除子文档中的_id,上面的命令将其从外部文档中排除,但不从子文档中排除。