如果存在则从字符串数组中删除否则插入它(猫鼬模式)

if present then delete from array of string else insert it (mongoose schema)

这是我的猫鼬模式:

const userSchema = new mongoose.Schema({
    username: String,
    password: String,
    solved: [{type: String}]
})

我想做的是,如果我的 query 出现在 solved 字符串数组中,那么我想删除它来自 solved 数组,如果 querysolved 数组中不存在,那么我想将 query 推入 solved array

我使用 findOneAndUpdate 进行了尝试,但它没有按照我想要的方式工作。

如有任何帮助,我们将不胜感激!谢谢!

你必须使用 $in 运算符在数组中找到具有查询的对象(如果有的话),然后使用经典更新

更新它

对于单个查询,您可以尝试 update with aggregation pipeline 从 MongoDB 4.2 开始,

  • $cond 检查字符串是否在 solved 数组中
  • 如果它在数组中,则过滤文档并使用 $filter
  • 删除匹配的字符串
  • else concat current solved array with new string using $concatArrays
let str = "a";
await UserModel.updateMany( // updateOne
  {}, // your query
  [{
    $set: {
      solved: {
        $cond: [
          { $in: [str, "$solved"] },
          {
            $filter: {
              input: "$solved",
              cond: { $ne: ["$$this", str] }
            }
          },
          { $concatArrays: ["$solved", [str]] }
        ]
      }
    }
  }]
)

Playground