qts
qts

Reputation: 1044

Updating mongodb and rendering it

I am learning mongodb, node.js and mongoose and want to update a mongodb and then display it on my browser. However my code only displays the results prior to my update even though I know the database has already been updated.

So for example I have two students called John and Tom, but when I update it with a third student called Fred and try to render the results, it only gives me John and Tom's details. Here is my code:

    create: function(req, res) {
        console.log('creating model');
        var newStud = new Models.Student({
                       surname: req.body.surname,
                       firstname: req.body.firstname,
                   }
        );
        console.log('saving model');
        newStud.save();
        console.log('rendering model');
        Models.Student.find({},
            function(err,result){
                console.log('finding results');
                if (err) {
                    throw err;}
                else {
                    console.log('returning results');
                    res.send(result);
                    } 
            }
        );
    },

When I update it with Fred's details, the console outputs the following:

creating model
saving model
rendering model
finding results
returning results
POST /students 200 21.629 ms - 5195

but the page only shows the following:

[
{
"surname": "Smith",
"firstname":"John"
"_id": "55bed36461521187445e5b53",
"__v": 0
},
{
"surname": "Peters",
"firstname":"Tom",
"_id": "55bed3f6c4faaa63464fc6df",
"__v": 0
},
]

I suspect my callback is not working properly. Can anyone explain why? Any help is most appreciated.

Upvotes: 0

Views: 109

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50416

The problem here is of course that .save() is an asynchronous method in itself. So to need to wait for it to respond before asking for data from the collection. Otherwise, it likely has not actually created the new item yet:

create: function(req, res) {
    console.log('creating model');
    var newStud = new Models.Student({
                   surname: req.body.surname,
                   firstname: req.body.firstname,
               }
    );
    console.log('saving model');
    newStud.save(function(err,doc) {           // <-- callback here
        console.log('rendering model');
        Models.Student.find({},
             function(err,result){
                if (err) {
                    throw err;}
                else {
                    console.log('returning results');
                    res.send(result);
                } 
             }
        );
    });
});

So basically you need to "wait" for the other .save() action to respond before you go query the whole collection to see the new addition.

Upvotes: 1

Related Questions