Mongoose instance .save() not working

前端 未结 7 706
情歌与酒
情歌与酒 2020-12-30 00:43

I have a problem with Mongoose and MongoDb

It is very interesting that only Model.update works and save never works and does not even fire

相关标签:
7条回答
  • 2020-12-30 01:42

    I am not going to delete this question because people may encounter this problem too. Actually problem was not related with MongoDb or Mongoose. When you call Object.save() responsibility chain is like below:

    1. Schema.pre("save")
    2. Save data to dabe
    3. Schema.post("save")

    So if you block pre("save") and don't call next() handler you won't be able to save your document. This was my case, I forgot the next() call inside an if statement and tried to find the error for more than 3 hours.

    user.pre("save", function(next) {
        if(!this.trial){
            //do your job here
            next();
        }
    }
    

    When this.trial == true, next handler won't be reachable.

    To prevent errors like this we should take care of branch coverage, reporters can show us untested codes. Your problem might be related with this too. Be sure you are calling next() if your document should be saved.

    Fixed Version

    user.pre("save", function(next) {
        if(!this.trial){
            //do your job here
        }
        next();
    }
    
    0 讨论(0)
提交回复
热议问题