node.js - 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?
解决方案
$push用于向数组添加一个元素。但是使用$each数组更新运算符,我们可以推送一个项目数组。
另外,我使用findOneAndUpdate
withnew: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
}
}
推荐阅读
- mergesort - 如何获得 3 次合并排序中的比较次数?
- c# - iPad 在导航上显示白屏而不是主页
- css - 模态对话框的大小和标题位置
- java - 为什么我会收到“java.lang.NoClassDefFoundError: kong/unirest/Unirest”?
- python - 在 Selenium/Python 中使用显式等待
- r - 为什么 filter 和 rowSums 不能一起工作?
- css - 使用 CSS Grid 每隔一行着色
- unity3d - 如何根据表面获得正确的运动方向矢量
- eclipse - 将.jar文件导入eclipse进行编辑
- python-3.x - pycharm 错误:包“pandas”需要不同的 Python:3.5.2 不在“>=3.5.3”中