MongoDB(Mongoose)更新数组中的元素

rggaifut  于 2022-11-13  发布在  Go
关注(0)|答案(3)|浏览(282)

我目前正在使用node.js express构建REST-Api,但不知道如何更新/添加scores Array中的元素。
下面是我的MongoDB集合中的一个文档(应该是这样的):

我的 Mongoose 模型:

const challengesSchema = new mongoose.Schema({
    createdBy:{
        type:String,
        required: true
    },
    mapType:{
        type:String,
        required: true
    },
    time:{
        type:Number,
        required: true
    },
    numberOfMaps:{
        type:String,
        required: true
    },
    maps:{
        type:Array,
        required: true
    },
    pin:{
        type: String,
        required: true
    },
    takenBy:{
        type: Array,
        required: false
    }
})

基本上,我收到一个id,我可以用它来做Challenges.findById({challenge._id})。我想出了如何向takenBy Array添加一个对象,如下所示:

Challenges.findOneAndUpdate(
  { _id: challenge._id },
  {
    $push: {
      takenBy: user
    }
  }
);

如何将一个元素(score,如“20”)添加到数组'takenBy'中的scores数组中?

gz5pxeao

gz5pxeao1#

您可以像这样使用filtered positional operator $一次推送score并计算新的TotalScore。

router.put("/challenges/:id/:scoreId", async (req, res) => {
  let score = req.body.score;

  try {
    let result = await Challenges.findByIdAndUpdate(
      req.params.id,
      {
        $push: { "takenBy.$[inner].scores": score },
        $inc: {
          "takenBy.$[inner].TotalScore": score
        }
      },
      {
        arrayFilters: [{ "inner._id": req.params.scoreId }],
        new: true
      }
    );

    if (!result) return res.status(404);

    res.send(result);
  } catch (err) {
    console.log(err);
    res.status(500).send("Something went wrong");
  }
});

测试

让我们有这个现有的文件:

{
    "_id" : ObjectId("5e08fe4c0bc1b932e8726a0f"),
    "maps" : [ ],
    "takenBy" : [
        {
            "_id" : "id1",
            "TotalScore" : NumberInt(100),
            "scores" : [
                NumberInt(20),
                NumberInt(60),
                NumberInt(20)
            ]
        },
        {
            "_id" : "id2",
            "TotalScore" : NumberInt(30),
            "scores" : [
                NumberInt(10),
                NumberInt(20)
            ]
        }
    ],
    "createdBy" : "5dfe0...",
    "mapType" : "World",
    "time" : NumberInt(2),
    "numberOfMaps" : "2",
    "pin" : "9558",
    "__v" : NumberInt(0)
}

如果我们想给id1增加一个50的分数,我们发送一个PUT请求(http://..../challenges/5e08fe4c0bc1b932e8726a0f/id1),其主体如下:

{
    "score": 50
}

结果会是这样的:

{
    "_id" : ObjectId("5e08fe4c0bc1b932e8726a0f"),
    "maps" : [ ],
    "takenBy" : [
        {
            "_id" : "id1",
            "TotalScore" : NumberInt(150),
            "scores" : [
                NumberInt(20),
                NumberInt(60),
                NumberInt(20),
                NumberInt(50)
            ]
        },
        {
            "_id" : "id2",
            "TotalScore" : NumberInt(30),
            "scores" : [
                NumberInt(10),
                NumberInt(20)
            ]
        }
    ],
    "createdBy" : "5dfe0...",
    "mapType" : "World",
    "time" : NumberInt(2),
    "numberOfMaps" : "2",
    "pin" : "9558",
    "__v" : NumberInt(0)
}

如您所见,分数已添加到相关项目数组中,并且其TotalScore也增加了50,TotalScore为150

v7pvogib

v7pvogib2#

您可以先撷取对象:

const updateChallenge = async (req,res) => {
    const challenge = await Challenges.findById(id);
    // Then you make duly changes to it with vanilla js:
    // Find which element in the array takenBy to update 
    // with regular js, methods like filter work or hardcode it

    challenge.takenBy[1].push(newElement);

    await challenge.save();
    // DONE! :)
}

当然,如果您愿意,也可以使用解构!

r6vfmomb

r6vfmomb3#

...如何更新/添加元素到scores Array。
我会先检索该数组......推送新值,然后更新。
类似于:

Challenges.findById(challenge._id,(err, db_result) => {
  if(err){
    console.log(err)              // error management
    //...
  }

  if(db_result){

    // Get the takenBy array
    let takenBy = db_result.takenBy

    // Who are we talking about... You need the second _id for that record
    let who_id = user._id

    let targetIndex = null
    let byWho = takenBy.filter((who, index) => {

      let gotYa = who._id === who_id
      if (gotYa){
        targetIndex = index
      }
      return gotYa  // Boolean used as a return for .filter()
    })

    if(byWho.length>0){
      console.log("Got someone... Index: ", targetIndex)
    }else{
      console.log("No one found?")
      return
    }

    // Push the new value using the index where to update.
    takenBy[targetIndex].scores.push(challenge.score)

    Challenges.updateOne({_id:challenge._id},{
        $set: {
          takenBy: takenBy
        }
      }, (err, data) => {
        console.log(data)
      }
    )

  }
});

相关问题