Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose save fails without error

As the title suggests I'm having problems with mongoose save method, which fails but does not produce an error.

I actually know why it fails, which is down to the userId field being marked as required but not being provided... but I don't know why it doesn't throw an error. I've exhausted google and stackoverflow looking at similar suggestions with no luck, so throwing it open to anyone who can help me!

Here's the code...

Model.js

var mongoose = require('mongoose');

var TimeSchema = new mongoose.Schema({
    client: String,
    matter: String,
    activity: String,
    tags: String,
    description: String,
    comments: [String],
    startTime: Date,
    startTimeUTC: Number,
    endTime: Date,
    endTimeUTC: Number,
    duration: Number, 
    durationRnd: Number,    
    durationUnits: Number,  
    billable: Boolean,
    rate: Number,
    total: Number,
    user: String,
    userId: { type: mongoose.Schema.ObjectId, required: true }
}, {safe: true});

mongoose.model("Time", TimeSchema);


Controller.js

exports.addTime = function (req, res) {

    console.log('Adding time: ' + JSON.stringify(req.body));
    var time = new Time(req.body);
    time.save(function (err) {
        if (err) { res.send({'error' : err}); }
        res.send(time);
    });
}

EDIT - To clarify the callback is being called, take the following code for example.

exports.addTime = function (req, res) {

    console.log('Adding time: ' + JSON.stringify(req.body));
    var time = new Time(req.body);
    console.log("time = " + time);
    // TODO user
    time.save(function (err) {
        if (err) { handleError(res, err); }
        console.log("ok");
        Time.findById(time._id, function (err, found) {
            console.log("found = " + found);
        });
        res.send(time);

});

}

and here's the console output

Adding time: {"description":"test","client":"","matter":"","activity":"","rate":
"","startTime":"2013-11-30T19:58:43.000Z","startTimeUTC":"1385841523000","endTim
e":"2013-11-30T19:58:45.000Z","endTimeUTC":"1385841525000","startLocale":"19:58"
,"startTimeLocale":"19:58:43","endLocale":"19:58","endTimeLocale":"19:58:45"}
time = { description: 'test',
  client: '',
  matter: '',
  activity: '',
  rate: null,
  startTime: Sat Nov 30 2013 19:58:43 GMT+0000 (GMT Standard Time),
  startTimeUTC: 1385841523000,
  endTime: Sat Nov 30 2013 19:58:45 GMT+0000 (GMT Standard Time),
  endTimeUTC: 1385841525000,
  startTimeLocale: '19:58:43',
  endTimeLocale: '19:58:45',
  _id: 529a43750a366b6419000001,
  comments: [] }
ok
POST /api/times 200 14ms - 313b
found = null
like image 485
Jon Miles Avatar asked Nov 30 '13 19:11

Jon Miles


People also ask

What does save () do in Mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.

What is markModified?

markModified(), it manually sets the array column that we are trying to update as modified and this makes mongoose detect the column change and updates the DB. /** * Marks the path as having pending changes to write to the db.

Does Mongoose save return a Promise?

While save() returns a promise, functions like Mongoose's find() return a Mongoose Query . Mongoose queries are thenables. In other words, queries have a then() function that behaves similarly to the Promise then() function. So you can use queries with promise chaining and async/await.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.


3 Answers

It is very possible to run into this error by naively not connecting to the database. Has happened several times to me. Make sure your mongoose.connect() is in place.

like image 125
Ali Avatar answered Oct 20 '22 14:10

Ali


Problem solved, thanks to robertkelp.

Here's my revised code in case if ever helps anyone, but it appears the error was being thrown I just wasn't handling it correctly.

exports.addTime = function (req, res) {

    console.log('Adding time: ' + JSON.stringify(req.body));
    var time = new Time(req.body);
    time.save(function (err) {
        if (err) { 
            handleError(res, err);
        }
        else {
            res.send(time);
        }
    });
}
like image 27
Jon Miles Avatar answered Oct 20 '22 13:10

Jon Miles


My Problem was not solved by using findOne, it was solved by defining the fields i updated , in the model schema. so my code was like that:

          User.findOne({email:data.userData.email}, function (err, user) {
                    if (!err && user!=undefined){
                        console.log(user);
                        var userDiscounts = user.discounts;
                        for(var i=0;i<userDiscounts.length;i++){

                            if (userDiscounts[i]!=undefined && userDiscounts[i].code=="XXXXXX"){
                                userDiscounts[i].claimed = true;

                                console.log('discount claimed');

                            }
                        }
                        user.discounts = userDiscounts;
                        user.fbDiscountClaimed = true;
                        user.save(function(err) {
                            if (err) console.log(err);
                            console.log('Saved Hashve-FB as claimed');


                        });
                    }


                });
            }
        }

But the schema of the discount and user model was missing the definition of types of user.discounts so i added the following:

  var UserSchema = new Schema({
  name: String,
  email: { type: String, lowercase: true },
   role: {
   type: String,
   default: 'user'
 },
  hashedPassword: String,
  provider: String,
  salt: String,
  messages:[],
  discounts:[{
  "name": String,
  "description": String,
  "created_at": String,
  "updated_at": String,
  "code": String,
  "claimed": Boolean
    }
    ],
   facebook: {},
   fbDiscountClaimed:false,
    twitter: {},
  google: {},
  github: {}
  });
like image 3
shacharsol Avatar answered Oct 20 '22 14:10

shacharsol