我目前正在使用Mongoose进行项目,但是我一直陷入Mongoose populate()方法的问题。
问题是我无法在数组中的对象内部填充对象。
export type Model = {
Id: number,
Name: string
}
// Get the raw response, with the real type for that response
const response = await Axios.get<{ id: number, name: string }>(source);
// Transform it into a new object, with the type you want
const model: Model = _.mapKeys(response,
(value, key) => _.upperFirst(key) // Turn camelCase keys into PascalCase
);
有什么方法可以在数组中填充嵌套对象?
如果您能回答我的问题,那就太好了。预先谢谢你。
// * I simplified the code below.
// Profile Document
Profile = model('Profile', new Schema({
_user: {
type: Schema.Types.ObjectId,
ref: 'User',
},
posts: [
{
type: Schema.Types.ObjectId,
ref: 'Post',
// Post = {
// _id: Number,
// _poster: {
// type: Schema.Types.ObjectId,
// ref: 'User',
// }
// };
},
],
}));
// app.js
const profile = await Profile.findOne({ _user: userId })
.populate('_user') // it works
.populate('posts') // it works too
.populate('posts._poster'); // it doesn't work
答案 0 :(得分:0)
我已经测试了您的模式,效果很好,请您测试一下并告诉我
const profile = await Profile.findOne({
_id: '5f108ed7ecc4881a6c35e27b',
})
.populate('_user')
.populate({
path: 'posts',
populate: {
path: '_poster',
model: 'User',
},
})
.exec();
console.log(profile);