使用Mongoose更新MongoDB集合中的多个文档实例。 save()不是功能
在这里蒙古Newbe。当标签删除时,我在文档帖子中获取了以下功能,以更新文档帖子中的引用(删除它们)。当我调用我的GraphQl API时,这是我得到的:
message": "posts.save is not a function"
GQL Resolver中的功能:
async deleteTag(root, { id }, context) {
const posts = await Post.find();
const tag = await Tag.findById(id);
if(!tag){
const error = new Error('Tag not found!');
error.code = 404;
throw error;
}
posts?.forEach(async (post) => {
await post.tags.pull(id);
})
await posts.save()
await Tag.findByIdAndRemove(id);
return true;
}
这是帖子模型:
const PostSchema = new Schema({
body: {
type: String,
required: true
},
tags: {
type: [Schema.Types.ObjectId],
ref: 'Tag',
required: false
},
});
这是标签模型:
const TagSchema = new Schema(
{
name: {
type: String,
required: true
},
},
{ timestamps: true }
);
看起来我无法称呼方法 save()在由 erocy.find()返回的对象上
,我在其他函数中使用了相同的模式,区别在于我使用 .findbyid()
是否有任何解决方案?咨询和最佳实践Advide非常欢迎。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须单独保存帖子:
或使用 与操作员。
fwiw,您可能应该通过仅选择列出的特定标签的文档来限制匹配
post
文档的数量:You have to save the posts individually:
Or use
Model.updateMany()
combined with the$pull
operator.FWIW, you should probably limit the number of matching
Post
documents by selecting only documents that have the specific tag listed: