在此解析器中,我无法填充嵌套在帖子“收藏夹”数组中的对象“作者”:
updateFavourites: async ({ _id, post, action }, req) => {
if (!req.isAuth) {
throw new Error("Not Authenticated!")
}
try {
const user = await User.findOne({ _id: _id }).populate([
{
path: 'favourites',
model: 'Post',
populate: {
path: 'author',
model: 'User',
}
},
])
if (!user) throw new Error("A User by that ID was not found!")
const postTest = await Post.findOne({ _id: post })
if (!postTest) throw new Error("A Post by that ID was not found!")
if (action === "add") {
user.favourites.forEach(fav => {
if (post.toString() === fav._id.toString()) {
throw new Error("Duplicate Favourite!")
}
})
user.favourites.push(post)
} else {
user.favourites.pull(post)
}
user.updated_at = moment().format()
await user.save()
return {
...user._doc
}
} catch (err) {
throw err
}
},
如果我在user.save()之后第二次检索到用户,则可以得到想要的结果,但我宁愿通过一次调用数据库来实现:
updateFavourites: async ({ _id, post, action }, req) => {
if (!req.isAuth) {
throw new Error("Not Authenticated!")
}
try {
const user = await User.findOne({ _id: _id })
if (!user) throw new Error("A User by that ID was not found!")
const postTest = await Post.findOne({ _id: post })
if (!postTest) throw new Error("A Post by that ID was not found!")
if (action === "add") {
user.favourites.forEach(fav => {
if (post.toString() === fav._id.toString()) {
throw new Error("Duplicate Favourite!")
}
})
user.favourites.push(post)
} else {
user.favourites.pull(post)
}
user.updated_at = moment().format()
await user.save()
const newUser = await User.findOne({ _id: _id }).populate([
{
path: 'favourites',
model: 'Post',
populate: {
path: 'author',
model: 'User',
}
},
])
return {
...newUser._doc
}
} catch (err) {
throw err
}
},
我要传递_id(即用户_id),post(即发布id_id)和action(其是字符串),并根据字符串值从收藏夹数组中推送或拉出帖子。