代码之家  ›  专栏  ›  技术社区  ›  cubefox

mongodb:从嵌套引用数组中提取一项

  •  0
  • cubefox  · 技术社区  · 7 年前

    我有一个嵌套的引用数组

    const userSchema = new Schema(
      {
        _id: Schema.Types.ObjectId,
        name: String,
       posts: [{ type: Schema.Types.ObjectId, ref: "Post" }]
      }
    );
    

    我想从这个数组中删除一个引用,我认为这很容易使用

     User.update({ name: currentName}, { $pull: { posts: postId }});
    

    这一点和变化类似

     User.update(
        { name: currentName},
        { $pull: { posts: mongoose.Types.ObjectId(postId) } }
      );
    

    或使用 findOneAndUpdate

    postId 格式如下所示 "5c150b855999681f7423aacb"

    1 回复  |  直到 7 年前
        1
  •  1
  •   krbalaji    7 年前
    User.findOneAndUpdate({
    _id: mongoose.Types.ObjectId('YOUR_DATA_ID')
    },
    { name: currentName,
    { $pull: { posts: mongoose.Types.ObjectId(postId) } }
    );