尝试更新是否存在文档,否则创建一个新文档

时间:2020-04-02 12:17:23

标签: mongodb mongoose

我的目标是更新文档,如果存在,则创建一个新文档。

如果文档存在,则将状态更新为1

{
    "participants": ["currentUserId", "targetedUserId"],
    "status": 1
    "_id": "5e85c139eeaa68224dbc7a2f",
    "__v": 0
}

如果该文档不存在,请创建与上面相同的记录

    {
        "participants": ["currentUserId", "targetedUserId"],
        "status": 1
        "_id": "5e85c139eeaa68224dbc7a2f",
        "__v": 0
    }

我的模式

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const MatchSchema = new Schema({
  participants: [{ type: Schema.Types.ObjectId, ref: "User" }],
  matchStatus: Number
});

module.exports = mongoose.model("Match", MatchSchema);

路由器

app.get('/test', () => {
   try {
    let query = {
      participants: {
        $all: [
          { $elemMatch: { $eq: currentUserId } },
          { $elemMatch: { $eq: targetedUserId } }
        ]
      }
    };
    let update = { expire: new Date() };
    let options = { upsert: true, new: true, setDefaultsOnInsert: true };
    let potentialMatch = await Match.findOneAndUpdate(query, update, options);
    // I want to update the status as well, but not sure how to do it.
    res.json(potentialMatch);
  } catch (err) {
    res.json(err.message);
  }
})

我一直在获取新记录,currentUserIdtargetedUserId的ID已经存在于我的数据库中,它应该显示存在的版本

{
    "participants": [],
    "_id": "5e85c139eeaa68224dbc7a2f",
    "__v": 0
}

0 个答案:

没有答案