Reputation: 310
I'm trying to figure out how to write to a MongoDB using Mongoose and Node.js without waiting for the response. The typical way to write to MongoDB is either to use the callback syntax or use the await/async pattern. Both of these patterns don't execute the query unless you specify a call back or await the response.
Is there a way to write to MongoDB in a 'best-effort' fashion? I.e. just make the call, don't wait for the response, and if it succeeds great, and if not, no problem.
EDIT:
Code:
Async/await pattern:
const doc = await Product.findByIdAndUpdate('prod1', {$inc: {viewed: 1}});
console.log(doc);
Callback pattern
Product.findByIdAndUpdate('prod1', {$inc: {viewed: 1}, func(err, doc) {
console.log(doc)
});
Both of these wait for the response.
Upvotes: 2
Views: 1699
Reputation: 13775
You can do the write using w:0 write concern setting. This will instruct MongoDB to do the write, but not waiting for feedback. For example:
conn.db('test').collection('test').insertOne({'a': 1}, {'w': 0}, function(err, res) {
assert.equal(null, err);
console.log(res);
})
The default write concern is w:1
(wait for confirmation from the node you're connecting to). If you check the res
output of the code above using w:1
, it will show:
...
insertedCount: 1,
...
In contrast, using w:0
will show:
...
insertedCount: undefined,
...
Note: although writes will return quickly with best-effort using this setting, this is essentially UDP for your writes. Use at your own risk.
Upvotes: 4