Sle*_*aur 63 javascript json mongoose mongodb node.js
我在运行查询后从MongoDB返回了一个JSON值.问题是我不想返回与我的返回相关联的所有JSON,我尝试搜索文档并且没有找到正确的方法来执行此操作.我想知道如果可能的话,如果是的话,这样做的正确方法是什么.示例:在DB中
{
user: "RMS",
OS: "GNU/HURD",
bearded: "yes",
philosophy: {
software: "FOSS",
cryptology: "Necessary"
},
email: {
responds: "Yes",
address: "rms@gnu.org"
},
facebook: {}
}
{
user: "zuckerburg",
os: "OSX",
bearded: "no",
philosophy: {
software: "OSS",
cryptology: "Optional"
},
email: {},
facebook: {
responds: "Sometimes",
address: "https://www.facebook.com/zuck?fref=ts"
}
}
Run Code Online (Sandbox Code Playgroud)
如果字段存在于用户,但是如果它不返回另一个字段,那么返回字段的正确方法是什么.对于上面的例子,我想返回[email][address]RMS的[facebook][address]字段和扎克伯格的字段.如果一个字段为空,我试图找到这个,但它似乎没有工作.
.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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*yHK 70
我并不完全清楚"返回一个字段"是什么意思,但你可以使用一个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;
}
});
Run Code Online (Sandbox Code Playgroud)
don*_*kup 36
如果您只想为填充的文档返回一些特定字段,则可以通过将字段名称语法作为第二个参数传递给populate方法来完成此操作.
Model
.findOne({ _id: 'bogus' })
.populate('the_field_to_populate', 'name') // only return the Persons name
...
Run Code Online (Sandbox Code Playgroud)
小智 28
尝试这样做:
User.find(options, '_id user email facebook').populate('facebook', '_id pos').exec(function (err, users) {
Run Code Online (Sandbox Code Playgroud)
Sca*_*aux 18
现在你能做的是:
.populate('friends', { username: 1, age: 1})
Run Code Online (Sandbox Code Playgroud)
Nav*_*mar 17
尝试这样做:
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);
}
Run Code Online (Sandbox Code Playgroud)
在下面的查询中,我检索了与条件匹配的文章,show=true检索到的数据title and createdAt 还检索了文章的类别,只有类别的标题和它的 id。
let articles = await articleModel
.find({ show: true }, { title: 1, createdAt: 1 })
.populate("category", { title: 1, _id: 1 });
Run Code Online (Sandbox Code Playgroud)
小智 8
对于单个级别的填充,您可以使用-> populate('user','name email age')
对于嵌套群体
populate({
path:'posts',
populate({
path:'user'
select:'name email age'
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39988 次 |
| 最近记录: |