Reputation:
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:
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');
}
Upvotes: 1
Views: 660
Reputation: 300
My reps too low to add a comment so excuse me for using an answer. I'd guess that the problem is the kind of loop you've used, but I can't tell without seeing more code.
If you've done array.forEach
you're going to have a bad time. You'll want to do for(let i in array)
type loop for async stuff.
Alternatively you can compile all the ops you want to do by mapping your array then doing upsertMany
on your collection.
Upvotes: 2