I'm using Mongoose's findOneAndUpdate method, and can't seem to get any useful information back from it. I've tried using the Query that comes back from calling it (in updatedUser), but it returns null; I've also tried including the callback argument, but when I do that I get null back for both err and doc.
Context: I'm using Jest to build a test suite, and writing a test for this function. I have had the function working in my application outside of the test suite, and while I have changed parts of the function I haven't changed anything in the findOneAndUpdate call, except for adding the callback argument.
Expected behavior: Either 'err' or 'doc' doesn't return null so I at least know what's happening.
I've worked with Mocha and I'm learning Jest, and I've discovered a couple of other entertaining things that Jest does. I know from experience that this is most likely me missing something fairly obvious, but I'd love to be able to blame something else for once. :)
updateUser.js:
const updateUser = async (user) => {
console.log('user in updater:', user);
const updatedUser = await User.findOneAndUpdate(
{ _id: user._id },
{
$set: {
name: user.name,
email: user.email,
password: user.password,
ageRange: user.ageRange,
gender: user.gender,
accountCreatedAt: user.accountCreateAt,
meetingPlaces: user.meetingPlaces,
flags: user.flags,
tokens: user.tokens,
}
},
{ new: true },
(err, doc) => {
console.log(err, doc);
}
);
//placeholders until I get some kind of usable response from findOneAndUpdate
return {err: false, res: 'cat'};
};
terminal output:
console.log server/db/crud_Users/updateUser.js:8
user in updater: { _id: 5b1aa9a146b59048dd86dbc2,
name: 'test',
email: '[email protected]',
password: 'testtest',
ageRange: '1',
gender: 'Female',
accountCreatedAt: '2018-06-08T11:06:57-05:00',
meetingPlaces: [],
flags: [],
tokens: [],
homeLocations: [],
hostedEvents: [],
attendingEvents: [],
__v: 0 }
console.log server/db/crud_Users/updateUser.js:28
null null
console.log server/db/crud_Users/updateUser.js:32
updatedUser: null
I thank you for explaining the issue that well.
It is mentioned in the official documentation of MongoDB here that findOneAndUpdate updates the first document in the collection that matches the request and return the original document.
I supposed that both err and doc are null because of the document that you want to update doesn't exist in your collection. It is not mentioned in the documentation what is the behavior of findOneAndUpdate if there is no document that matches the query. So, I tried to go deeper into it.
I saw in the documentation (you can learn more about it here) that if the parameter upsert isn't mentioned, it will take false as a default value. And I saw here in the P.S. part that if upsert is false and the document doesn't exist, than doc will be null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With