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

如何确保模型键上没有重复数据?

  •  1
  • karolis2017  · 技术社区  · 7 年前

    这是我的用户模型:

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

    watched 和 watchLater 包含 串 一串 注视 我想删除或确保没有相同的 一串 在…上 晚点 反之亦然。最好的方法是什么?我必须分别查询这两个键、比较并写回数据库,还是有其他方法?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ashh    7 年前

    您可以将条件放入查询部分

    db.collection.update(
      { watched: { $ne: string } watchedLater: { $ne:string }}, 
      { $push: { watched: string }}
    )