mongoose doc.save在架构方法中失败而没有错误

时间:2013-01-04 01:47:36

标签: node.js mongoose

我正在使用mongoose:

var postSchecma = mongoose.Schema({
title: String,
body: String,
link: String,
voting: {
    has: {
        type: Boolean,
    default:
        false
    },
    canVoteFor: [mongoose.Schema.Types.Mixed],
    votedFor:{},
    voteDates:{}
},
comments: [mongoose.Schema.Types.Mixed],
date: {
    type: mongoose.Schema.Types.Mixed,
default:
    new Date().getTime()
}
}, {
    strict: false,
    safe:true
})

postSchecma.methods.vote = function(voteFor, callback) {
var self = this;
if(self.voting.canVoteFor.indexOf(voteFor) < 0) {
    callback(new Error('Error: Invalid Thing To Vote For'));
    return;
}
this.voting.voteDates[voteFor].push(new Date().getTime())
this.voting.votedFor[voteFor]++
s = this;
this.save(function(err) {
    if(err) {
        callback(err)
    }
    console.log(err);
    console.log("this:"+ s);
    callback(s)
})
}

在postSchecma.methods.vote中,this.voting.votedFor [voteFor]的值是正确的。但是当我查询db时,它是旧的值。如果它有助于我在2个文件中使用db,并且方法可能不完全重复。 我也知道它是mongoose的东西,因为我可以使用mongoDB GUI将记录更改为不同的值,并且它工作正常。 如果您需要更多信息,请告诉我 谢谢, Porad说

2 个答案:

答案 0 :(得分:9)

架构中定义为{}Mixed的任何字段都必须明确标记为已修改,或者Mongoose不会知道它已更改且Mongoose需要保存它。

在这种情况下,您需要在save之前添加以下内容:

this.markModified('voting.voteDates');
this.markModified('voting.votedFor');

查看Mixed here上的文档。

答案 1 :(得分:0)

事实证明,这也有时适用于非Mixed物品,正如我痛苦地发现的那样。如果重新分配整个子对象,则还需要在其中使用markModified。至少......有时候。我没有用来得到这个错误,然后我做了,没有改变任何相关的代码。我的猜测是它是一个猫鼬版升级。

实施例!说你有......

personSchema = mongoose.Schema({
    name: {
        first: String,
        last: String
    }
});

...然后你打电话......

Person.findById('whatever', function (err, person) {
    person.name = {first: 'Malcolm', last: 'Ocean'};
    person.save(function (err2) {
        // person.name will be as it was set, but this won't persist
        // to the database
    });
});

...除非您在person.markModified('name')

之前致电save,否则您将度过难关

(或者,同时调用person.markModified('name.first') person.markModified('name.last') ......但这在这里看起来显得比较差)

相关问题