从 Mongoose 返回某些字段

在运行查询之后,MongoDB 将返回一个 JSON 值。问题是我不想返回与我的返回相关的所有 JSON,我试图搜索文档,但没有找到合适的方法。我想知道如果这是可能的,如果是这样,什么是正确的方式这样做。例如: 在尸体上

{
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"
}
}

如果某个字段存在,但是没有返回另一个字段,那么返回该字段的正确方法是什么。对于上面的例子,我想返回 RMS 的 [email][address]字段和 Zuckerberg 的 [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");
}
}
}
113229 次浏览

试着这样做:

User.find(options, '_id user email facebook').populate('facebook', '_id pos').exec(function (err, users) {

我不是很清楚你所说的“返回一个字段”是什么意思,但是你可以使用一个 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;
}
});

如果只想为填充的文档返回几个特定的字段,可以通过将字段名语法作为第二个参数传递给填充方法来实现。

Model
.findOne({ _id: 'bogus' })
.populate('the_field_to_populate', 'name') // only return the Persons name
...

参见 猫鼬种群的田间选择

现在你可以做的是:

  .populate('friends', { username: 1, age: 1})

试着这样做:

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

你可以试试:

Post.find({_id: {$nin: [info._id]}, tags: {$in: info.tags}}).sort({_id:-1})
.populate('uid','nm')
.populate('tags','nm')
.limit(20).exec();

你可以在下面尝试使用,

 Model
.find()
.populate({path: 'foreign_field', ['_id', 'name']}) // only return the Id and Persons name
...

只是为了补充上面的答案,如果你想要 include everything but only exclude certain attributes,你可以做以下几点:

.populate('users', {password: 0, preferences: 0})

Hi for me it worked for me i populated user field using the populate 密码: —— >

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

我正在直接得到结果。这里的 userName、 userProfile 图像是我们有选择地需要的字段,其语法是: —— >

 .populate("user field to populate","fields to display with spaces between each of them " , "modelName ")

每个参数都应该用反逗号。

下面是我收到的输出。还有一件事你不必担心填充子文档 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
}
]

在下面的查询中,我检索了符合条件 show=true的文章,检索到的数据 title and createdAt也检索了文章的类别,只检索了类别的标题和 ID。

let articles = await articleModel
.find({ show: true }, { title: 1, createdAt: 1 })
.populate("category", { title: 1, _id: 1 });

对于单个级别的填充,可以使用 -> populate('user','name email age')

对于巢居种群来说

populate({
path:'posts',
populate({
path:'user'
select:'name email age'
})
})

我卡在这个问题上。我想人口和 用户字段链接到博客文章。 Using populate only returned everything including the 密码. By specifying fields as an array it works fine.

//code emitted for brevity

await Blog.findById(ID).populate("author", ["firstName", "lastName",
"profilePicture", "_id"])

//

This is the result of the response

Response