Node.js mongoose doc.save失败,架构方法中没有错误

Node.js mongoose doc.save失败,架构方法中没有错误,node.js,mongoose,Node.js,Mongoose,我正在使用猫鼬: var postSchecma = mongoose.Schema({ title: String, body: String, link: String, voting: { has: { type: Boolean, default: false }, canVoteFor: [mongoose.Schema.Types.Mixed], votedFor:{}, voteDates:{} },

我正在使用猫鼬:

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=函数(voteFor,回调){
var self=这个;
if(自投票.可投票或指数(投票或指数)<0){
回调(新错误('Error:Invalid Thing To Vote'));
返回;
}
this.voting.voteDates[voteFor].push(new Date().getTime())
这个.投票.投票++
s=这个;
此.save(函数(err){
如果(错误){
回调(错误)
}
控制台日志(err);
console.log(“this:+s”);
回拨
})
}
在postSchecma.methods.vote中,this.voting.votedFor[voteFor]的值是正确的。但当我查询数据库时,它是旧值。如果有帮助的话,我在2个文件中使用db,方法可能不是完全重复的。 我也知道它与mongoose有关,因为我可以使用mongoDB GUI将记录更改为不同的值,并且工作正常。 如果你需要更多信息,请告诉我, 谢谢
Porad

模式中定义为
{}
混合的任何字段必须明确标记为已修改,否则Mongoose将不知道它已更改,并且Mongoose需要保存它

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

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

正如我痛苦地发现的那样,参见
Mixed
上的文档,这有时也适用于非
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
    });
});
…除非在
save
之前调用
person.markModified('name')

(或者,也可以同时调用
person.markModified('name.first')
person.markModified('name.last')
…但在这里,这似乎明显较低)

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