Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose doc.save fails without error in schema method

Using mongoose i am doing:

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

and

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

in postSchecma.methods.vote the value of this.voting.votedFor[voteFor] is correct. but when I query the db it is the old value. if it helps i am using the db in 2 files and the methods may not be exact duplicates. I also know it is something with mongoose because I can change the record to a different value with a mongoDB GUI and it works fine. let me know if you need any more info, thanks, Porad

like image 445
Ari Porad Avatar asked Jun 11 '26 00:06

Ari Porad


1 Answers

Any field in your schema that's defined as {} or Mixed must be explicitly marked as modified or Mongoose won't know that it has changed and that Mongoose needs to save it.

In this case you'd need to add the following prior to the save:

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

See docs on Mixed here.

like image 128
JohnnyHK Avatar answered Jun 12 '26 16:06

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!