Whats the proper way to wrap a mongo query/insert in a function to make it reusable? I have an update operation that may take place in various places and want to only write it once and reuse it. I'm using MongoJS to interface w/ the MongoDb API.
When I take something like the following:
mongo.myt.update(
{'_id': req._id},
{
$addToSet: {
"aggregate.clientIds": req.myt.clientIds
},
$inc: {"aggregate.seenCount": 1},
$set: {
"headers": req.myt.headers,
"ip": req.myt.ip
},
$setOnInsert: {
'_id': req.myt._id,
'derived': req.myt.derived
}
},
{upsert: true},
function (err, savedId) {
if (err || !savedId) console.log("failed to save :" + req.myt + " because of " + err);
else console.log("successfully saved :" + req.myt);
});
And wrap it with a simple function like:
function mongoInsert(req) {
//same query as above
}
Then call it using:
mongoInsert(req);
I don't see any impact to speed when profiling. Should I be adding a callback to the wrapper function, is that needed? I was expecting it would have some performance impact and need to be done differently.
So a few questions.
Does the approach above calling mongoInsert() get called synchronously and block until the async mongo update is done?
If it does become sync, I would expect a performance impact which I didnt see. So is the approach I took ok to use?
And if not what would be the correct way to do this?
mongoInsert()
is still asynchronous because it's calling an asynchronous function ( mongo.myt.update()
). Even if you don't add a callback function, it won't magically become synchronous.
The way you wrote it now is "fire-and-forget" : somewhere in your code you call mongoInsert()
, your code will continue to run while the update is taking place, and since you don't pass a callback the calling code cannot get informed about the result of the update (right now, you're just logging the result to console).
It's a design decision whether or not this is acceptable.
You could make the callback optional for situations where you do want to get informed about the update result:
function mongoInsert(req, callback) {
callback = callback || function() {}; // dummy callback when none is provided
mongo.myt.update(..., function(err, savedId) {
...log status here...
callback(err, savedId);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.