一些背景知识,我有一个使用 MongoDB 作为数据库的应用程序的快速后端。 Auth0 作为身份提供者存在。
我有一个
addTeamUser
异步函数:
findOneAndUpdate
代码如下图:
const addTeamUser = async (req) => {
// Get team_id from JWT token
const team_id = req.auth.team_id;
const data = req.body;
// Joi validation for the email body
const { error } = schema.user.validate(data, { abortEarly: false });
if (error) {
return { message: error.message, statusCode: 400 };
}
try {
// Call auth0 management API and create new user with the email provided and custom team_id in app_metadata
const createdUser = await managementAPI.createUser({
email: data.email,
connection: 'Username-Password-Authentication',
password: "changeme",
app_metadata: {
team_id: team_id,
},
});
// Add user to local database if Management API returned a success
const user = {
id: createdUser.user_id,
email: createdUser.email
};
const doc = await Team.findOneAndUpdate(
{ team_id },
{ $push: { users: user } },
{ new: true });
return {
statusCode: 201,
users: doc.users,
message: "User added successfully"
}
} catch (err) {
console.error('Error creating user:', err);
return { message: 'An error occurred, try again later', statusCode: 500 };
}
};
现在这就像一个魅力......除了当用户被插入本地数据库时,它有时会插入两次并且我最终在我的数组中有两个相同的用户。
我读了一些书,显然我不能同时使用 await 和回调,但无论我做什么来修复它,它都会执行两次。
这是我的团队架构以获得更多背景信息:
const teamSchema = new Schema({
team_id: {
type: String,
required: true
},
name: {
type: String,
required: true,
trim: true,
},
users: [
{
id: {
type: String,
unique: true,
required: true,
trim: true
},
email: {
type: String,
unique: true,
required: true,
trim: true
}
}
],
}, {
_id: false // This disables the automatic _id field for subdocuments
});
请告诉我这个错误是怎么回事,我该如何解决?
findOneAndUpdate
方法将用户插入两次的原因是因为 {new:true}
标志。所以删除它会解决你的问题。有关更多信息,请查看上一个问题: