这个问题在这里已有答案:
这是一个检查mongoose重复记录的函数。在这种情况下,name
和email
是唯一字段,因此如果数据库中存在具有相同名称或电子邮件的记录,则无法插入新记录:
const checkIfDatabaseHasUsersWithSameNameAndEmail = async () => {
uniques = ['name', 'email'];
uniques.map((field) => {
let query = {};
query[field] = data[field];
query.deleted = false;
let result = await model.findOne(query); <== ERROR: await is a reserved word
if (result) {
errors.push({
field: field,
message: 'A record already exists in database for ' + field + '=' + data[field]
});
}
});
if (errors.length > 0)
return errors;
}
schema.statics.create = function (data) {
let errors = await checkIfDatabaseHasUsersWithSameNameAndEmail(); <== ERROR: await is a reserved word
if (errors)
throw new Error(errorMessages);
let company = new this(data);
return company.save();
}
运行时我在代码中指出了以下错误:await is a reserved word
这是我第一次使用async / await,所以可能我是以错误的方式做的。我的目标是按顺序运行que唯一测试(findOne),如果一切顺利,保存新寄存器。
该错误是因为您正在尝试等待某些内容,但尚未将该函数声明为异步。我没有用猫鼬测试它,但它看起来像这样。
async function checkIfDatabaseHasUsersWithSameNameAndEmail(data) {
const uniques = ['name', 'email'];
return Promise.all(uniques.map(async (field) => {
const query = {};
query[field] = data[field];
query.deleted = false;
return model.findOne(query);
}));
}
schema.statics.create = async function create(data) {
try {
const results = await checkIfDatabaseHasUsersWithSameNameAndEmail(data);
results.forEach((result) => {
console.log(`Here's the issue: ${JSON.stringify(result)}`);
throw new Error('Do something about it.');
});
const company = new this(data);
return company.save();
} catch (error) {
throw error;
}
};