Recently, I've been intrigued by the behavior of adding a callback to the mongoose findOneAndUpdate function and how it leads to saving data twice in the database.
public async addPersonAsFavorite(userId: string, friendId: string) {
if (!await this.isPersonAlreadyFriend(userId, friendId)) {
const friendList = FriendsList.findOneAndUpdate(
{ _id: userId },
{ $push: { friendsList: friendId } },
{ upsert: true, new: true },
(err, data) => {
if (err) console.error(err);
return data;
}
);
return friendList;
}}
public async isPersonAlreadyFriend(userId: string, friendId: string) {
let isFriendFound = false;
await FriendsList.findById(userId, (err, data) => {
if (data) {
console.log(data.friendsList);
}
if (err) console.error(err);
if (data && data.friendsList.indexOf(friendId) > -1) {
isFriendFound = true;
console.log('already friend');
} else {
console.log('not friend');
isFriendFound = false;
}
})
return isFriendFound;
}
Upon removal of the callback function, the data is saved only once.
EDIT: Additionally, after observing the second piece of code and encountering a new question. It was noticed that when multiple attempts are made to add a friend quickly, duplication occurs as the system initiates the process before the previous operation completes its check, leading to multiple entries being added unintentionally.
How can the system be configured to ensure completion of the DB write operation before allowing the function to be triggered again?