如何使用 Node、MongoDB 和 Mongoose 增加嵌套在数组中的值服务器端?
How do I increment a value server side nested in an array using Node, MongoDB and Mongoose?
我正在尝试创建一个路由来更新嵌套数组中对象中的特定值。我的节点控制台出现 404 错误。我几乎可以肯定这不是实现它的方法,但我的代码将给出我想要实现的目标的想法:
router.put('/getProfile/:profile_id/addWin'), function (req, res) {
UserProfile.findOne({
UserID : req.params.profile_id //Find the correct Profile
}, function (err, profile) {
if (err)
res.send(err);
profile.Drafts.findByID({ //Find the corrct Draft in the Profile
_id : req.body.DraftID
}, function (err, draft) {
if (err)
res.send(err);
draft.Wins += 1; //Increment the wins
})
profile.save(function (err) { //Save the profile
if (err)
res.send(err);
res.json({
message : 'Win added!'
});
});
});}
这是控制台中的错误:
PUT /api/getProfile/575ecce6924295bc21000005/addWin 404 5.128 ms - -
路线应该找到正确的配置文件(这适用于我的其他路线),使用 profile_id
,然后访问 Drafts array
并找到正确的 Draft 和 increment the wins
。我该如何实现?
在我的请求正文中,我只是将 DraftID and the profileID
作为参数发送,并存储在配置文件对象的用户 ID 属性 中。
这是我第一次尝试 MEAN stack
所以我还不太舒服。
你必须像这样在路由器中将回调函数 (req,res) 作为第二个参数传递:(在 url 之后没有关闭函数)
router.put('/getProfile/:profile_id/addWin', function (req, res) {
UserProfile.findOne({
UserID : req.params.profile_id //Find the correct Profile
}, function (err, profile) {
if (err)
res.send(err);
profile.Drafts.findByID({ //Find the corrct Draft in the Profile
_id : req.body.DraftID
}, function (err, draft) {
if (err)
res.send(err);
draft.Wins += 1; //Increment the wins
})
profile.save(function (err) { //Save the profile
if (err)
res.send(err);
res.json({
message : 'Win added!'
});
});
});
});
我正在尝试创建一个路由来更新嵌套数组中对象中的特定值。我的节点控制台出现 404 错误。我几乎可以肯定这不是实现它的方法,但我的代码将给出我想要实现的目标的想法:
router.put('/getProfile/:profile_id/addWin'), function (req, res) {
UserProfile.findOne({
UserID : req.params.profile_id //Find the correct Profile
}, function (err, profile) {
if (err)
res.send(err);
profile.Drafts.findByID({ //Find the corrct Draft in the Profile
_id : req.body.DraftID
}, function (err, draft) {
if (err)
res.send(err);
draft.Wins += 1; //Increment the wins
})
profile.save(function (err) { //Save the profile
if (err)
res.send(err);
res.json({
message : 'Win added!'
});
});
});}
这是控制台中的错误:
PUT /api/getProfile/575ecce6924295bc21000005/addWin 404 5.128 ms - -
路线应该找到正确的配置文件(这适用于我的其他路线),使用 profile_id
,然后访问 Drafts array
并找到正确的 Draft 和 increment the wins
。我该如何实现?
在我的请求正文中,我只是将 DraftID and the profileID
作为参数发送,并存储在配置文件对象的用户 ID 属性 中。
这是我第一次尝试 MEAN stack
所以我还不太舒服。
你必须像这样在路由器中将回调函数 (req,res) 作为第二个参数传递:(在 url 之后没有关闭函数)
router.put('/getProfile/:profile_id/addWin', function (req, res) {
UserProfile.findOne({
UserID : req.params.profile_id //Find the correct Profile
}, function (err, profile) {
if (err)
res.send(err);
profile.Drafts.findByID({ //Find the corrct Draft in the Profile
_id : req.body.DraftID
}, function (err, draft) {
if (err)
res.send(err);
draft.Wins += 1; //Increment the wins
})
profile.save(function (err) { //Save the profile
if (err)
res.send(err);
res.json({
message : 'Win added!'
});
});
});
});