MongoDB找不到刚刚创建的文档



我有一个代码,它在循环中与用户逐行处理一个文件,并为每个迭代处理下一个代码。如果用户是唯一的,MongoDB会将其插入到集合中,否则它只是更新信息。唯一ID是用户的电子邮件。问题是文件中也有用户的副本

文件看起来像:

  1. 约翰-john@gmail.com
  2. 新约翰的名字-john@gmail.com(重复但更改了名称(
  3. 标记-mark@gmail.com
  4. 。。。休息

我的代码以插入1的方式处理它。John在数据库中,但问题是mongo数据库无法找到刚刚创建的带有电子邮件的用户john@gmail.com并取(2。新约翰的名字-john@gmail.com)作为唯一的用户。

注意:等待调用在异步函数内部,所以它们应该可以正常工作。

这是它的代码:

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');
}

我的重复次数太低,无法添加评论,请原谅我使用了答案。我想问题出在你使用的循环类型上,但如果没有看到更多的代码,我就无法判断。

如果你已经完成了array.forEach,你会过得很糟糕。您将希望为异步内容执行for(let i in array)类型的循环。

或者,您可以通过映射数组然后对集合执行upsertMany来编译所有要执行的操作。

最新更新