I have a code that processes a file with users line by line in a loop and for each iteration works next code. If a user is unique, MongoDB inserts it in the collection otherwise it's just update the info. Unique ID is email of the user. The problem is the file has also duplicates of the user inside it.
The file looks like:
- John - [email protected]
- New John name - [email protected] (duplicate but with changed name)
- Mark - [email protected]
- ...rest
My code processes it in the way that it insert 1. John in the DB, but the problem is that mongo DB can't find just created user with email [email protected] and takes (2. New John name - [email protected]) as a unique user.
Note: await calls are inside async function, so they should work fine.
Here is the code for it :
try {
let user = await User.findOne({ email: email }).exec();
if (user) { // here mongoose should find 1. John which was created on before loop iteration but it retuns null
let update = {
name: newName,
email: newEmail
}
let updateUser = await User.findByIdAndUpdate(
user._id,
{$set: update},
{new: true}
);
} else {
let newUser = new User({
name: name,
email: email
});
let saveUser = await newUser.save();
res.send('Users uploaded successfully');
} catch (err) {
console.error(err.message);
res.send('Server error');
}
line by line in a loop and for each iteration. The problem is, you can't useawaitinside.forEach()(but you can inside aforloop - Jeremy Thille