Reputation: 1800
I am confused about the parameters that are passed through to the promise function of write operations.
For example, the docs for updateOne say that the callback is an instance of updateWriteOpCallback which has parameters error
and result
.
db.collection.('my-collection')
.updateOne({_id: someObjectID}, {$set: someChanges}, function(err, result){
console.log(err); //null
console.log(result); //CommandResult
}
In the above example, if the operation is successful, err
is correctly set to null and result
contains the result.
However, if I choose to us a promise instead of a callback:
db.collection.('my-collection')
.updateOne({_id: someObjectID}, {$set: someChanges})
.then((err, result) => {
console.log(err); //CommandResult
console.log(result); //undefined
}
The first parameter err
is actually giving me what should be in result
, and result
is undefined. Is there an explanation for why this happens?
Upvotes: 1
Views: 1143
Reputation: 2161
This is because that isn't how promises work. When a promise gets rejected, you are supposed to catch it with the promise.catch()
method, not promise.then()
.
So:
promise.then()
is used to get the result of the resolve()
operation.promise.catch()
is used to get the result of the reject()
operation.Thus your code should be:
db.collection.('my-collection')
.updateOne({_id: someObjectID}, {$set: someChanges})
.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err);
});
Upvotes: 4