node.js - Updating mongodb and rendering it -


i learning mongodb, node.js , mongoose , want update mongodb , display on browser. code displays results prior update though know database has been updated.

so example have 2 students called john , tom, when update third student called fred , try render results, gives me john , tom's details. here 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 update fred's details, console outputs following:

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

but page shows following:

[ { "surname": "smith", "firstname":"john" "_id": "55bed36461521187445e5b53", "__v": 0 }, { "surname": "peters", "firstname":"tom", "_id": "55bed3f6c4faaa63464fc6df", "__v": 0 }, ] 

i suspect callback not working properly. can explain why? appreciated.

the problem here of course .save() asynchronous method in itself. need wait respond before asking data collection. otherwise, has not created 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 need "wait" other .save() action respond before go query whole collection see new addition.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -