Javascript 使用 .populate() 从 Mongoose 返回某些字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26691543/
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
Return certain fields with .populate() from Mongoose
提问by Sleep Deprived Bulbasaur
I'm getting returned a JSON value from MongoDB after I run my query. The problem is I do not want to return all the JSON associated with my return, I tried searching the docs and didn't find a proper way to do this. I was wondering what if it is at possible, and if so what is the proper way of doing such. Example: In the DB
运行查询后,我从 MongoDB 返回了一个 JSON 值。问题是我不想返回与我的返回相关的所有 JSON,我尝试搜索文档但没有找到正确的方法来执行此操作。我想知道如果可能的话会怎样,如果可能的话,这样做的正确方法是什么。示例:在数据库中
{
user: "RMS",
OS: "GNU/HURD",
bearded: "yes",
philosophy: {
software: "FOSS",
cryptology: "Necessary"
},
email: {
responds: "Yes",
address: "[email protected]"
},
facebook: {}
}
{
user: "zuckerburg",
os: "OSX",
bearded: "no",
philosophy: {
software: "OSS",
cryptology: "Optional"
},
email: {},
facebook: {
responds: "Sometimes",
address: "https://www.facebook.com/zuck?fref=ts"
}
}
What would be the proper way of returning a field if it exists for a user, but if it doesn't return another field. For the example above I would want to return the [email][address]field for RMS and the [facebook][address]field for Zuckerburg. This is what I have tried to find if a field is null, but it doesn't appear to be working.
如果用户存在一个字段,但如果它不返回另一个字段,那么返回字段的正确方法是什么。对于上面的示例,我想返回[email][address]RMS 的[facebook][address]字段和 Zuckerburg的字段。如果一个字段为空,这就是我试图找到的,但它似乎不起作用。
.populate('user' , `email.address`)
.exec(function (err, subscription){
var key;
var f;
for(key in subscription){
if(subscription[key].facebook != null ){
console.log("user has fb");
}
}
}
回答by JohnnyHK
I'm not completely clear on what you mean by "returning a field", but you can use a lean()query so that you can freely modify the output, then populate both fields and post-process the result to only keep the field you want:
我不完全清楚“返回字段”是什么意思,但您可以使用lean()查询,以便您可以自由修改输出,然后填充两个字段并对结果进行后处理以仅保留您想要的字段:
.lean().populate('user', 'email.address facebook.address')
.exec(function (err, subscription){
if (subscription.user.email.address) {
delete subscription.user.facebook;
} else {
delete subscription.user.email;
}
});
回答by dontmentionthebackup
If you only want a few specific fields to be returned for the populated documents, you can accomplish this by passing the field name syntax as the second argument to the populate method.
如果您只想为填充的文档返回几个特定的字段,您可以通过将字段名称语法作为第二个参数传递给 populate 方法来实现这一点。
Model
.findOne({ _id: 'bogus' })
.populate('the_field_to_populate', 'name') // only return the Persons name
...
See Mongoose populate field selection
请参阅猫鼬填充字段选择
回答by scuencag
Try to do this:
尝试这样做:
User.find(options, '_id user email facebook').populate('facebook', '_id pos').exec(function (err, users) {
回答by S Kumar
Try to do this:
尝试这样做:
applicantListToExport: function (query, callback) {
this
.find(query).select({'advtId': 0})
.populate({
path: 'influId',
model: 'influencer',
select: { '_id': 1,'user':1},
populate: {
path: 'userid',
model: 'User'
}
})
.populate('campaignId',{'campaignTitle':1})
.exec(callback);
}
回答by Scaraux
Now what you can do is :
现在你可以做的是:
.populate('friends', { username: 1, age: 1})
回答by Tran Hoang Hiep
you to try :
你试试:
Post.find({_id: {$nin: [info._id]}, tags: {$in: info.tags}}).sort({_id:-1})
.populate('uid','nm')
.populate('tags','nm')
.limit(20).exec();
回答by Prashant Ghimire
Just to complement the answers above, if you want to include everything but only exclude certain attributes, you can do the following:
只是为了补充上面的答案,如果您想包含所有内容但只排除某些属性,您可以执行以下操作:
.populate('users', {password: 0, preferences: 0})
回答by Pankaj Shukla
Hi for me it worked for me i populated user field using the populate code : --->
嗨对我来说它对我有用我使用填充代码填充了用户字段:--->
async function displayMessage(req,res,next){
try{
let data= await Msg.find().populate("user","userName userProfileImg","User")
if(data===null) throw "Data couldn ot be loaded server error"
else {
res.status(200).json(data)
}
} catch(err){
next(err)
}
}
i am directly getting the result . Here the fields userName , userProfile image are the ones that ive required selectively and the syntax for populate is :-->
我直接得到结果。这里的字段 userName , userProfile image 是我有选择地需要的字段,填充的语法是:-->
.populate("user field to populate","fields to display with spaces between each of them " , "modelName ")
every parameter should be in inverted comma's.
每个参数都应该用引号引起来。
Below is the output i recieve.One more thing you don't have to worry about the populating sub-document id you will automatically get them.
下面是我收到的输出。还有一件事,您不必担心填充子文档 ID,您将自动获取它们。
[
{
"_id": "5e8bff324beaaa04701f3bb9",
"text": "testing message route",
"user": {
"_id": "5e8bf062d3c310054cf9f293",
"userName": "boss",
"userProfileImg": "img"
},
"__v": 0
},
{
"_id": "5e8bff8dd4368a2858e8f771",
"text": "testing message route second",
"user": {
"_id": "5e8bf062d3c310054cf9f293",
"userName": "boss",
"userProfileImg": "img"
},
"__v": 0
},
{
"_id": "5e8c0c08e9bdb8209829176a",
"text": "testing message route second",
"user": {
"_id": "5e8bf062d3c310054cf9f293",
"userName": "boss",
"userProfileImg": "img"
},
"__v": 0
},
{
"_id": "5e8c0e0bcb63b12ec875962a",
"text": "testing message route fourth time",
"user": {
"_id": "5e8bf062d3c310054cf9f293",
"userName": "boss",
"userProfileImg": "img"
},
"__v": 0
}
]
回答by Naresh Ramoliya
you can try using below,
你可以尝试使用下面,
Model
.find()
.populate({path: 'foreign_field', ['_id', 'name']}) // only return the Id and Persons name
...

