[英]Undesirable structure when populating sub document with Mongoose
A user has project IDs but I also want to store some additional project info: 用户具有项目ID,但我也想存储一些其他项目信息:
const userSchema = new Schema({
...
projects: [{
_id: {
type: Schema.Types.ObjectId,
ref: 'Project',
unique: true, // needed?
},
selectedLanguage: String,
}]
});
And I want to populate with the project name so I'm doing: 我想用项目名称填充,所以我在做:
const user = await User
.findById(req.user.id, 'projects')
.populate('projects._id', 'name')
.exec();
However user.projects
gives me this undesirable output: 但是user.projects
给了我这个不想要的输出:
[
{
selectedLanguage: 'en',
_id: { name: 'ProjectName', _id: 5a50ccde03c2d1f5a07e0ff3 }
}
]
What I wanted was: 我想要的是:
[
{ name: 'ProjectName', _id: 5a50ccde03c2d1f5a07e0ff3, selectedLanguage: 'en' }
]
I can transform the data but I'm hoping that Mongoose can achieve this out the box as it seems a common scenario? 我可以转换数据,但我希望Mongoose可以实现这一目标,因为这似乎很常见? Thanks. 谢谢。
尝试这样的populate({path:'projects', select:'name selectedLanguage'})
Seems like there are two options here: 似乎这里有两个选择:
1) Name the _id
field something more semantic so it's: 1)将_id
字段命名为更多语义,因此:
{
selectedLanguage: 'en',
somethingSemantic: { _id: x, name: 'ProjectName' },
}
2) Flatten the data which can be done generically with modern JS: 2)扁平化数据,这可以用现代JS通用地完成:
const user = await User
.findById(req.user.id, 'projects')
.populate('projects._id', 'name')
.lean() // Important to use .lean() or you get mongoose props spread in
.exec();
const projects = user.projects.map(({ _id, ...other }) => ({
..._id,
...other,
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.