问题描述
我看过很多例子,如何更新一个数组,像这样猫鼬查找/更新子文档和这个使用nodejs/mongoose部分更新子文档
I've seen a lot of examples, how to update an array, like this oneMongoose find/update subdocumentand this onePartial update of a subdocument with nodejs/mongoose
但是我的目标是更新特定字段,例如在用户输入数据的表单中.
but my objective is to update a specific field, for example in a Form, where user enters data.
我正在使用ejs进行模板制作.
I'm using ejs for templating.
这是代码
为清楚起见,这是用户模式
For clarity , here is User's Schema
var UserSchema = mongoose.Schema({
resume: {
education: [{ type: String}],
}
});
路由代码
router.post('/update-resume', function(req, res) {
User.findById(req.user._id, function(err, foundUser) {
// Take a look over here, how do I update an item in this array?
if (req.body.education) foundUser.resume.education.push(req.body.education);
foundUser.save(function(err) {
if (err) return next(err);
req.flash('message', 'Successfully update a resume');
return res.redirect('/update-resume')
});
});
});
如果您看一下上面的代码,我的目标是查询要恢复的用户数据,并更新其当前值.
If you take a look at the code above, my objective is to query a user data which is resume, and update its current value.
前端代码
<form role="form" method="post">
<div class="form-group">
<label for="education">Education:</label>
<% for(var i = 0; i < user.resume.education.length; i++) { %>
<input type="text" class="form-control" name="education" id="education" value="<%= user.resume.education[i] %>">
<% } %>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
前端代码确实有效,它在每个user.resume.education
数组中进行迭代,并显示该数组中的所有值.但是我该如何更新呢?
Frontend code does work, it iterate in each user.resume.education
array, and show all the values in the array. But how do I update it?
推荐答案
由于对教育数组使用了.push()
,猫鼬不知道此字段已更改,因此需要用函数,所以猫鼬会知道该字段已更改,因此,在您推入教育数组后,请使用:
Since you're using .push()
to the education array, mongoose don't know that this field has changed, you need to specify it with the markModified()
function so mongoose will know that this field has changed, so, after you push to the education array use:
foundUser.markModified('resume.education');
,然后使用save()
功能
更新:
router.post('/update-resume', function(req, res) {
User.findById(req.user._id, function(err, foundUser) {
// Take a look over here, how do I update an item in this array?
if (req.body.education) foundUser.resume.education.push(req.body.education);
foundUser.markModified('resume.education'); // <-- ADDITION
foundUser.save(function(err) {
if (err) return next(err);
req.flash('message', 'Successfully update a resume');
return res.redirect('/update-resume')
});
});
});
这篇关于如何在猫鼬中保存子文档的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!