Search code examples
node.jsvalidationmongoose

Validate Array of Objects Before Creating Any with Mongoose


I have a Backend with Node-Mongoose. I have a Schema "Customer" with some fields (like Name and Avatar). I have a function to create a new Customer. Everything works fine. Now I need to create many customers, I do this by sending an array of objects as req.body instead of a sole object.

I am able to do it, but if any of the objects has a validation error (no valid email or name), it is NOT stored in the database. However, the ones that are allright, are indeed stored.

Problem is: I need to validate the whole array of objects before creating any document. If any of the objects is invalid, none of them should be created.

I have been searching but I can't find anything. Any help?

My original function is very simple:

exports.createCustomer = catchAsync(async (req, res, next) => {
const newCustomer = await Customer.create(req.body)
if (!newCustomer) return next(new AppError('The customer could not be created', 404))

res.status(201).json({
    status: 'success',
    data: {
        newCustomer
    }
})

})


Solution

  • I write an example for how to solve your question,suppose want to verify the email address's length is correct. 

    //schema
    
    const customerSchema = new mongoose.Schema({
        email: {
        type: String,
        required: [true, 'email must input'],
        minlength: [5, 'min length'],
        maxlength: [50, 'max length'],
      },
    });
    
    
    
    app.post('/api/v1/customers', async (req, res, next) => {
      const customers = req.body;
      //validate array
      const validationPromises = customers.map(customer => {
        const newCustomer = new Customer(customer);
        return newCustomer.validate();
      });
    
      try {
        await Promise.all(validationPromises);
      } catch (error) {
        return next(new Error(`validation failed: ${error.message}`, 400));
      }
      const newCustomers = await Customer.insertMany(customers);
    
      if (!newCustomers) {
        return next(new Error('insert failed', 500));
      }
    
      res.status(201).json({
        status: 'success',
        data: {
          newCustomers
        }
      })
    });