我想从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)
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)
Gáb*_*mre 13
另一种方法:
.toJSON()
删除它_id
和__v
字段的模式.toJSON()
发送到客户端的所有数据库对象item.id === 'something'
因为typeof id === 'string'
,而不是ObjectId
._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)
我知道这很难看.但到目前为止,这是我最好的坏主意.
在 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)