首页 > 解决方案 > Finding and Updating record - Mongoose

问题描述

I am building an API to store friends names for a game, I have built the API to receive the post request as so :

exports.addFriends = async (req, res) => {
  try {
    console.log('hit');
    console.log(req.body.friendNames);
    const addUser = await User.updateOne(
      { uniqueid: req.body.uniqueid },
      { $push: { friendNames: [req.body.friendNames] } }
    );
    res.json({
      addUser
    });
  } catch (error) {
    console.log(error);
  }
};

ad the post request as

      const friends = await axios.post('/api/v1/users/add/friends', {
          uniqueId: this.uniqueid,
          friendNames: [
            {
              userName: 'test',
              region: 'euw'
            }
          ]
        });

My API is being hit as a see the logs, but no record is made. My User Schema is as so

const userSchema = new mongoose.Schema({
  uniqueid: {
    type: String,
    required: true,
    trim: true
  },
  summonerName: {
    type: String
  },
  friendNames: [
    {
      userName: String,
      region: String
    }
  ]
});


I get no error and the request seems to go through, but no records are added. Any ideas?

标签: node.jsmongodbexpressmongoose

解决方案


$push用于向数组添加一个元素。但是使用$each数组更新运算符,我们可以推送一个项目数组。

另外,我使用findOneAndUpdatewithnew:true选项来检索更新的文档,因为 updateOne 不返回更新的文档。

exports.addFriends = async (req, res) => {
  try {
    console.log(req.body.friendNames);

    const addUser = await User.findOneAndUpdate(
      { uniqueid: req.body.uniqueid },
      { $push: { friendNames: { $each: req.body.friendNames } } },
      { new: true }
    );

    res.json({ addUser });
  } catch (error) {
    console.log(error);
    res.status(500).send("Something went wrong");
  }
}

假设我们有这个现有的文档:

{
    "_id": "5e31c749f26d5f242c69f3aa",
    "uniqueid": "uniqueid1",
    "summonerName": "John",
    "friendNames": [
        {
            "_id": "5e31c749f26d5f242c69f3ab",
            "userName": "Max",
            "region": "Germany"
        }
    ],
    "__v": 0
}

让我们使用这个请求正文向控制器发送一个请求:

{
    "uniqueid": "uniqueid1",
    "friendNames": [
        {
            "userName": "Andrew",
            "region": "England"
        },
        {
            "userName": "Smith",
            "region": "USA"
        }
    ]
}

响应将是这样的:

{
    "addUser": {
        "_id": "5e31c749f26d5f242c69f3aa",
        "uniqueid": "uniqueid1",
        "summonerName": "John",
        "friendNames": [
            {
                "_id": "5e31c749f26d5f242c69f3ab",
                "userName": "Max",
                "region": "Germany"
            },
            {
                "_id": "5e31c763f26d5f242c69f3ad",
                "userName": "Andrew",
                "region": "England"
            },
            {
                "_id": "5e31c763f26d5f242c69f3ac",
                "userName": "Smith",
                "region": "USA"
            }
        ],
        "__v": 0
    }
}

推荐阅读