Monday, 29 May 2017

Why may a mongoose document not get saved?

I've been using the following middleware for sometime, then suddenly it stops saving new docs. Further explanation in the comments

var body = req.body;

new ordersModel (body).save(function(err, newOrder, rowCount) {
    if (err) throw err;
    console.log(rowCount) // logs 1

    updateEstimatedTime(newOrder); /* updateEstimatedTime runs but inside
   it, trying to find this document newOrder returns null,
   meaning it was never saved */
});

If I try something like

var pleaseWork = new ordersModel (body);
console.log(pleaseWork) // it dumps a loaded mongoose object
pleaseWork.save(function(err, newOrder, rowCount) { 

So why doesn't it get persisted? I also tried reloading the server several times with this at the top just in case I was getting collections loaded during server setup

ordersModel.find({}, 'customer', function (err, docs) {
    if (err) throw err;
    console.log(docs)
}) 

But it just returns the documents that existed before this fault began. I've triple checked the model name, it's the same all over the script. What could the code be lacking? I have seen some examples online also that suggested something in the region of

var pleaseWork = new ordersModel ();
pleaseWork.foo = body.foo;
pleaseWork.bar = body.bar;
pleaseWork.john = body.john;

console.log(pleaseWork) // dumps a loaded mongoose object
pleaseWork.save(function(err, newOrder, rowCount) { 

Now, this is not feasible for me; the ordersModel table has more than 10 columns-- dropping the body object in the model's constructor is sane enough and worked the last time the program was run.

Although I don't think it's necessary but if you need to see my model, I can make that available. Also the full server code in case you need to deploy and test.



via Mmayboy

No comments:

Post a Comment