【问题标题】:Perform push and pull together in mongodb through mongoose Expresss通过 mongoose Express 在 mongodb 中执行 push 和 pull
【发布时间】:2020-08-18 14:42:50
【问题描述】:

我陷入了必须同时进行推拉的情况。

我有类别和帖子的架构,其中帖子可以有多个类别,类别将使用像这样的猫鼬的对象引用方法有多个帖子的数组-

    PostSchema= new mongoose.Schema({
      title:{type:String, required:true},
      content:{type:String, required:true}, 
      categories:[{type:mongoose.Schema.Types.ObjectId, ref:'Categories'}]     
})

与我为类别设置架构的方式相同-

   CatSchema = new mongoose.Schema({
      name:{type:String, required:true},
      slug:{type:String, required:true}, 
      posts:[{type:mongoose.Schema.Types.ObjectId, ref:'Posts'}]     
})

现在,当我创建帖子时,我会将 postId 推送到 Categories 集合的所有类别中。

但是,当我尝试更新 POST 并选择与本次早些时候不同的类别时,会出现问题。

我仍然可以在新选择的类别中推送更新的 postId,但是如何从那些在更新期间未选择但在创建期间选择的类别中提取 postId。他们仍然按照最初推送的方式存储这个 postId。

更清楚地说,我想在更新类别时更新类别集合中的帖子数组。欢迎所有类型的解决方案,包括创建模式或解决此特定问题的更好方法。 谢谢

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-schema


    【解决方案1】:

    我了解到,对于本次更新,您需要 postID、arrayOldCaretoryiesID 和 arrayNewCategoriesID。

    让我们从当前帖子中查找并删除您需要的类别。

    const deletedCatFromPost = await Post.updateOne({ _id: postID }, { $pull: { categories: arrayOldCaretoryiesID } })
    

    其次,通过 ID 数组从旧类别中删除您需要的帖子。

    const removedOldCategories = await Categories.updateMany({_id:{$or: arrayOldCaretoryiesID }},{ $pull:{ posts: postID }})
    

    最后,通过 ID 数组向新类别添加一个新的 postID。

    const addNewCategories = await Categories.updateMany({_id: { $or: arrayNewCategoriesID} },{$push:{ posts: postID }})
    

    希望对你有帮助。

    更新:

    其次,通过 ID 数组从旧类别中删除您需要的帖子。

    const removedOldCategories = await Categories.updateMany({_id:{$in: arrayOldCaretoryiesID }},{ $pull:{ posts: postID }})
    

    【讨论】:

    • 感谢您提供可能的解决方案。无论如何,它在使用'$or,$in 时抛出错误(Error: Can't use $or)解决了我的问题,但逻辑仍然归功于你。
    • 我刚刚在我的电脑上试用过,它工作正常。您能否提供有关错误的更多信息或提供失败的代码。谢谢。
    • 即使我没有得到太多关于这方面的信息,它可能会出错的是这条小消息Error Can't use $or。我的架构与上面完全相同。我正在尝试的只是采取一系列新旧猫并尝试推拉帖子阵列。可能是这行 Mongo 文档解释它$or versus $in When using $or with <expressions> that are equality checks for the value of the same field, use the $in operator instead of the $or operator.
    • 你是对的,你应该使用 $in 而不是 $or。我会更新答案。
    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多