How to make a synchronous call with mongoose and nodejs

I am developing a client / server synchronization function. The client sends a bunch of changed events to the server. The server will create, delete, or change the status of the requested item. After the operation with the database, the server needs to send the resume back to the client.

The following is a snippet of my server-side code developed using mongoose and updated.

var EventModel = mongoose.model('Event', eventSchema); server.post("/sync", function (req, res, next) { var events = req.params.events; var created = [], deleted = [], updated = []; events.forEach(function (elem) { if (elem.status == 0) { // Delete EventModel.remove({ _id: elem.uuid }, function (err, event) { if (!err) deleted.push({uuid: elem.uuid}); }); } else if (elem.status == 1) { // Create and update uuid var event = new EventModel(elem); event.save(function (err, doc) { if (!err) { elem.uuid = event._doc._id; created.push(elem); } }); } else if (elem.status == 2) { // Update EventModel.findOne({ _id: elem.uuid }, function (err, event) { event.save(function (err, doc) { if (!err) updated.push({uuid:elem.uuid}); }); }); } }); // Notify client what are processed. // PROBLEM: created, deleted, updated are always empty! res.send({processed: {created: created, deleted: deleted, updated: updated}}); }); 

Since mongoose executes CRUD in asynchronous mode, the created , deleted and updated answer is always empty. Is there any way to allow mongoose operation in a series?

+7
mongoose synchronous restify
source share
1 answer

As pointed out in the comments, you can use the npm asynchronous module.

Alternatively, you may prefer to embed callbacks (but this can lead to what is known as a callback addon, namely a lot of nested callbacks) or use the mongoose.then () method - see http: // mongoosejs. com / docs / promises.html

Here you can do it.

 EventModel.remove(args).then((removeResponse) => { return EventModel.findOne(args); }).then((findResponse) => { // etc }) 

These requests will be executed synchronously.

+1
source share

All Articles