0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mendes
  • 17,489
  • 35
  • 150
  • 263

1 Answers1

1

The error is because you're trying to await something, but haven't declared the function async. I didn't test this with mongoose, but it will look something like this.

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;
  }
};
Brent Barbata
  • 3,631
  • 3
  • 24
  • 23