用户拥有项目ID,但我还想存储一些额外的项目信息:
const userSchema = new Schema({
...
projects: [{
_id: {
type: Schema.Types.ObjectId,
ref: 'Project',
unique: true, // needed?
},
selectedLanguage: String,
}]
});
我想填充项目名称,以便我做:
const user = await User
.findById(req.user.id, 'projects')
.populate('projects._id', 'name')
.exec();
然而user.projects
给了我这种不受欢迎的输出:
[
{
selectedLanguage: 'en',
_id: { name: 'ProjectName', _id: 5a50ccde03c2d1f5a07e0ff3 }
}
]
我想要的是:
[
{ name: 'ProjectName', _id: 5a50ccde03c2d1f5a07e0ff3, selectedLanguage: 'en' }
]
我可以转换数据,但我希望Mongoose能够实现这一目标,因为这似乎是常见的情况吗?感谢。
答案 0 :(得分:0)
尝试这样的事情
populate({path:'projects', select:'name selectedLanguage'})
答案 1 :(得分:0)
似乎这里有两个选项:
1)将_id
字段命名为更具语义性的内容,以便:
{
selectedLanguage: 'en',
somethingSemantic: { _id: x, name: 'ProjectName' },
}
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,
}));