Search code examples
node.jsmongodbmongoose

Mongoose instance .save() not working


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

Mongoose: 4.4.5 MongoDB: 3.0.8

Express Route

var mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1:27017/db");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(callback) {
    console.log("connection to db open")
});
var User = require("../models/user.js");

User Model

var user = new Schema({
    uid: { type: Number, required: true, unique: true},
    hwid: { type: String, default:""},
    bol:{type:String,default:""}
});

Update Enpoint

Working version: Model.update()

User.update({_id: id}, {
    uid: 5, 
}, function(err, numberAffected, rawResponse) {
    console.log(err);
})

Not working version and I have to solve this: Object.save()

User.find({_id:id}, function(err,user){
    if(err){
         console.log(err);
    }
    if(!user){
         console.log("No user");
    }else{
        user.uid = 5;
        user.save(function(err,news){
            console.log("Tried to save...");
        });
    }
    console.log("At least worked");
})

Even callback is not firing. Connection successfully opens. It never invokes callback.


  1. Tried to use var User = connection.model('User', schema) didn't work.

Solution

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