猫鼬嵌入式文档更新 [英] Mongoose embedded document updating

查看:86
本文介绍了猫鼬嵌入式文档更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对嵌入式文档更新有疑问.

I have a problem with embedded document update.

我定义的模式:

var Talk = new Schema({
    title: {
        type: String,
        required: true
    },
    content: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        required: true
    },
    comments: {
        type: [Comments],
        required: false
    },
    vote: {
        type: [VoteOptions],
        required: false
    },
});

var VoteOptions = new Schema({
    option: {
        type: String,
        required: true
    },
    count: {
        type: Number,
        required: false
    }
});

现在,我想使用给定的Talk id和VoteOption id更新vote.count++.我具有以下功能来完成这项工作:

Now I would like to update vote.count++, with given Talk id and VoteOption id. I have the following function to do the job:

function makeVote(req, res) {

    Talk.findOne(req.params.id, function(err, talk) {
        for (var i = 0; i < talk.vote.length; i++) {
            if (talk.vote[i]._id == req.body.vote) {
                talk.vote[i].count++;

            }
        }
        talk.save(function(err) {
            if (err) {
                req.flash('error', 'Error: ' + err);
                res.send('false');
            } else {
                res.send('true');
            }
        });
    });
}

一切都执行了,我取回了res.send('true'),但计数值没有改变.

Everything executes, I get back the res.send('true'), but the value on count does not change.

当我做一些console.log时,我看到它更改了值,但是talk.save只是没有将其保存在db中.

When I did some console.log I saw that it changed the value, but the talk.save just doesn't save it in db.

此外,对于找到嵌入式文档的_id的周期,我也很不满意.在猫鼬文档中,我读到了有关talk.vote.id(my_id)的信息,但这给了我没有id函数的错误.

Also I'm quite unhappy about the cycle just to find _id of embedded doc. In the mongoose documentation I read about talk.vote.id(my_id) but that gives me error of not having an id function.

推荐答案

在更新Mixed类型(似乎不是基本类型,因此还包括嵌入式文档)时,必须调用在文档上.在这种情况下,它将是:

When updating a Mixed type (which seems to be anything else than a basic type, so that also includes embedded documents), one has to call .markModified on the document. In this case, it would be:

talk.markModified("vote"); // mention that `talk.vote` has been modified

talk.save(function(err) {
    // ...
});

希望这对以后的人有所帮助,因为我无法很快找到答案.

Hope this helps someone in the future since I couldn't find the answer very quickly.

参考:

...猫鼬失去了自动检测/保存这些更改的能力.要告诉"猫鼬混合类型的值已更改,请调用文档的.markModified(path)方法,将路径传递到刚更改的混合类型.

... Mongoose loses the ability to auto detect/save those changes. To "tell" Mongoose that the value of a Mixed type has changed, call the .markModified(path) method of the document passing the path to the Mixed type you just changed.

这篇关于猫鼬嵌入式文档更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆