如何从模型数组中删除特定项目?

时间:2018-11-28 03:44:11

标签: mongodb mongoose

这是我的带有watchedwatchLater数组的用户模型:

const UserSchema = new mongoose.Schema(
  {
    email: { type: String, required: true, unique: true },
    watched: [{ type: Number }],
    watchLater: [{ type: Number }],
  },
  { timestamps: true },
)

我具有要从watchLater删除 id 并将其添加到watched的功能:

  async addToWatched(id) {
    const _id = this.getUserId()
    return await this.store.User.findByIdAndUpdate(
      { _id },
      // remove id from watchLater and add to watched,
      { new: true },
    )
  }

我该怎么做?

1 个答案:

答案 0 :(得分:0)

有点阅读文档。这似乎可行:

return await this.store.User.findByIdAndUpdate(
  { _id },
  // remove id from watchLater and add to watched,
  { $pull: { watchLater: id }, $addToSet: { watched: id } },
  { new: true },
)