Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating with mongoose, not returning any errors but neither updating

I am trying to learn CRUD with mongoose. I am only missing the update part. What am I doing wrong?

MY MODEL

var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({
    name: String,
    number: Number
});

mongoose.model('TestData', testSchema);

MY ROUTES

// get the models
var Test = mongoose.model('TestData');

PARAM
If the link has the 'test' as a url parameter, it will look if the object exist in the database, else return errors.

router.param('test', function(req, res, next, id){
    var query = Test.findById(id);

    query.exec(function(err, test){
        if(err){ return next(err); }
        if(!test){ return next(new Error('can\'t find test')); }
        req.test = test;
        return next();
    });
});

GET BY ID

    /* GET testdata/:id */
    router.get('/testingdata/:test', function(req, res, next){
        req.test.populate('test', function(err, test){
            res.json(test);
        });
    });

DELETE

/* DELETE testdata/:id */
router.delete('/testingdata/:test', function(req, res, next){
    req.test.remove('test', function(err, test){
        console.log('removed');
        res.json(test);
    });                         
});

MY PROBLEM
Now here comes my problem, if I try to update one, I am simply missing something.

/* PUT testdata/:id */
router.put('/testingdata/:test', function(req, res, next){
    req.test.update('test',{$set: {name: 'new data'}} , function(err, test){
        res.json(test);
    });                         
});

I am not getting any errors, but it is neither updating anything. It is even returning some data.

{
    "ok": 0,
    "n": 0,
    "nModified": 0
}
like image 555
Sigils Avatar asked May 04 '15 13:05

Sigils


People also ask

How do I update my Mongoose?

The save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware. For cases when save() isn't flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.

How does Mongoose update work?

When using Mongoose, it is very likely that you will want to update a document. One good method to use is the update() method. It matches a document based on the filter specified, and then makes the update based on the update supplied as well.

Why we use $set in Mongoose?

In the doc, it mentioned that: By default, if you don't include any update operators in doc, Mongoose will wrap doc in $set for you. This prevents you from accidentally overwriting the document.

What is Upsert in Mongoose?

Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.


2 Answers

Try without unneeded first argument (test), because the req.test is an instance of the Test model.

req.test.update({name: 'new data'} , function(err, test){
  res.json(test); // test would be `1` if success
});

The update method will not return object, and if you want to return object then use save:

req.test.name = 'new data';
req.test.save(function(err, test){
  res.json(test);
});
like image 187
Talgat Medetbekov Avatar answered Nov 07 '22 06:11

Talgat Medetbekov


Your problem is in that both the remove and the update methods, don't work on a model instance but require queries, like

{_id:id}

You update statement isn't matching anything, and I bet your remove endpoint won't work either.

If you want to operate on the live model instance on req.test then set the value on test directly and save the model:

req.test.name= 'new data';
req.test.save(...

Deleting a model is always going to require a new query as you can't delete an instance directly.

like image 45
Robert Moskal Avatar answered Nov 07 '22 05:11

Robert Moskal