Here is a function that checks on mongoose for duplicate records. In that case name
and email
are unique fields, so if a record with the same name or email is on database a new one cannot be inserted:
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();
}
When running I´m getting the following error pointed out on code: await is a reserved word
This is my first time using async/await, so probably I´m doing it the wrong way. My goal is to run que unique tests (findOne) in sequence and if everything goes fine save the new register.