node.js Mongoose 在没有 _id 字段的情况下检索数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9598505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose retrieving data without _id field
提问by Masiar
I would like to retrieve some data from a Mongoose setting in my Node.js application. I noticed that no matter what I write as field selection, I always get the _idfield. Is there a way not to fetch it?
This is how I do right now:
我想从我的 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);
});
And logs me the results which contain the _idfield.
并将包含该_id字段的结果记录给我。
回答by VisioN
Another way is to use text argument with prefix -which will exclude this or that field from the result:
另一种方法是使用带有前缀的文本参数-,它将从结果中排除这个或那个字段:
Entity.find({ ... }, '-_id field1 field2', function(err, entity) {
console.log(entity); // { field1: '...', field2: '...' }
});
回答by danmactough
_idmust be specifically excluded. For example,
_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);
});
回答by Gábor Imre
Another approach:
另一种方法:
- Augment the
.toJSON()of the schema that it deletes the_idand the__vfields - Call
.toJSON()on all DB objects sent to client - Extra benefit #1: you can use
item.id === 'something'becausetypeof id === 'string', notObjectId. - Extra benefit #2: When you got gan object back from the client and you want to search / update then you don't have to manually delete
_idbecause there is none, just anidwhich is ignored.
- 增加
.toJSON()它删除的架构的_id和__v字段 - 调用
.toJSON()发送到客户端的所有 DB 对象 - 额外好处#1:您可以使用
item.id === 'something'因为typeof id === 'string',而不是ObjectId。 - 额外好处#2:当您从客户端取回 gan 对象并且想要搜索/更新时,您不必手动删除,
_id因为没有,只是id被忽略。
Augmenting JSON:
增强 JSON:
mySchema.set('toJSON', {
virtuals: true,
transform: (doc, ret, options) => {
delete ret.__v;
ret.id = ret._id.toString();
delete ret._id;
},
});
So you can use:
所以你可以使用:
let item = (await MyCollection.findOne({/* search */}).exec()).toJSON();
if (item.id === 'someString') return item;
I know it's ugly. But it's the best bad idea that I have so far.
我知道这很丑。但这是我迄今为止最好的坏主意。
回答by Durja Arai
In 5.2.13 version of Mongoose (Sept 2018)- using the query builder approach the same can be converted to
在 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
}
}

