英文:
Mongoose - express server update specific index in array of objects
问题
我已创建一个自定义的 identifier
ID,尝试更新我的硬币以及第一个数组对象的 purchased
布尔值为真。
这是我的数据样式:
[
{
"identifier": "123456789",
"coins": 100,
"equipments": [
{
"item": "itemname",
"price": 100,
"gold": 10,
"level": 1,
"condition": 100,
"purchased": false
},
{
"item": "itemname2",
"price": 80,
"gold": 8,
"level": 1,
"condition": 100,
"purchased": false
}
],
"__v": 0
}
]
这是我的更新路由:
router.put("/update/:identifier", function(req, res){
User.find({identifier: req.params.identifier}, function(err, equipment) {
equipment.coins = 50;
equipment[0].equipments.purchased = true;
equipment[0].save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(equipment);
}
});
});
});
当我运行它时,什么都不发生,也没有出现任何错误。
英文:
I've created a custom identifier
ID and I'm trying to update my coins and aswell as the first
array object purchased bool to true.
this is how my data looks like
[
{
"identifier": "123456789",
"coins": 100,
"equipments": [
{
"item": "itemname",
"price": 100,
"gold": 10,
"level": 1,
"condition": 100,
"purchased": false
},
{
"item": "itemname2",
"price": 80,
"gold": 8,
"level": 1,
"condition": 100,
"purchased": false
},
],
"__v": 0
}
]
This is my update routes
router.put("/update/:identifier", function(req,res){
User.find({identifier: req.params.identifier}, function(err, equipment) {
equipment.coins= 50;
equipment[0].equipments.purchased = true;
equipment[0].save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(equipment);
}
});
});
});
When I run it nothing happens and it doesn't give any errors
答案1
得分: 2
这不是传统的方法。
你需要这样做。
router.put("/update/:identifier", function(req, res){
User.findOne({ identifier: req.params.identifier }, function(err, equipment) {
equipment.coins = 50;
equipment.equipments.purchased = true;
equipment.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(equipment);
}
});
});
});
额外提示: 我建议你使用 findAndUpdateOne()
英文:
This is not the conventional approach.
You need to do it like this.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
router.put("/update/:identifier", function(req,res){
User.findOne({identifier: req.params.identifier}, function(err, equipment) {
equipment.coins= 50;
equipment.equipments.purchased = true;
equipment.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(equipment);
}
});
});
});
<!-- end snippet -->
BONUS:I would suggest you to use findAndUpdateOne()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论