【问题标题】:How do i save a sub document's array in mongoose?如何在猫鼬中保存子文档的数组?
【发布时间】:2016-01-24 11:33:18
【问题描述】:

我看过很多例子,如何更新数组,比如这个 Mongoose find/update subdocument 和这个 Partial update of a subdocument with nodejs/mongoose

但我的目标是更新特定字段,例如在用户输入数据的表单中。

我正在使用 ejs 进行模板化。

这是代码

为了清楚起见,这里是用户的架构

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

});

如果你看一下上面的代码,我的目标是查询一个恢复的用户数据,并更新它的当前值。

前端代码

<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 数组中进行迭代,并显示数组中的所有值。但是如何更新呢?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    由于您使用.push() 到教育数组,猫鼬不知道该字段已更改,您需要使用markModified() 函数指定它,以便猫鼬知道该字段已更改,所以,推送到教育数组后使用:

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

    【讨论】:

    • 检查要点,不知何故,我不知道如何实现。
    • 第二个正文解析器如何知道哪个req.body属于哪个索引?
    • 您需要使用您在问题中显示的相同代码,只需在 pushsave 操作之间添加 markModified 行
    • 只是为了让你知道,我做了你所做的,它不断向数组推送一个新值而不是更新它。跟前端还是后端有关系吗?
    • 当然会,你有一个String数组,你认为它会如何更新值?您的教育数组中的每个元素都只是一个字符串,而不是一个带有 ID 的对象,我的建议,在这里阅读有关人口的信息:mongoosejs.com/docs/populate.html,这就是我认为您的意思
    猜你喜欢
    • 2017-12-05
    • 1970-01-01
    • 2020-07-27
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    相关资源
    最近更新 更多