查找和更新记录-猫鼬

时间:2020-01-29 16:57:15

标签: node.js mongodb express mongoose

我正在构建一个用于存储游戏好友名称的API,我已经构建了该API来接收发布请求:

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);
  }
};

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

我的API正在被查看,但没有记录。我的用户架构就这样

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


我没有收到任何错误,请求似乎已通过,但未添加任何记录。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

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

此外,我将findOneAndUpdatenew: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
    }
}