Mongoose embedded document updating

后端 未结 2 1118
無奈伤痛
無奈伤痛 2021-02-14 09:40

I have a problem with embedded document update.

My defined Schemas:

var Talk = new Schema({
    title: {
        type: String,
        required: true
            


        
相关标签:
2条回答
  • 2021-02-14 10:23

    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.


    Reference:

    ... 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.

    0 讨论(0)
  • 2021-02-14 10:26

    It's because you are trying to save your talk object before the callback which increments count has been fired. Also, did you make sure to instantiate your Talk schema? eg:

    var talk = new Talk();
    

    However, if all you want to do is increment your count variable, mongo supports atomic, in-place updates which you may find useful:

    talk.find( { _id : req.body.vote }, { $inc: { count : 1 } } );
    

    have a look at: http://www.mongodb.org/display/DOCS/Updating#Updating-%24inc

    0 讨论(0)
提交回复
热议问题