How to save array of objects in mongoose

To save an array of objects in Mongoose, you can follow these steps:

  1. Define a schema for the objects in the array using Mongoose’s Schema class.
  2.     
        const mongoose = require('mongoose');
        const Schema = mongoose.Schema;
    
        const objectSchema = new Schema({
          key1: String,
          key2: Number,
          ...
        });
    
        const arraySchema = new Schema({
          objects: [objectSchema]
        });
    
        const ArrayModel = mongoose.model('ArrayModel', arraySchema);
        
      

    In the example above, objectSchema defines the schema for each object in the array, while arraySchema defines the schema for the array itself. The ArrayModel is the Mongoose model that represents the array in the database.

  3. Create an instance of the ArrayModel and populate the objects array with the desired data.
  4.     
        const arrayInstance = new ArrayModel({
          objects: [
            { key1: 'value1', key2: 1 },
            { key1: 'value2', key2: 2 },
            ...
          ]
        });
        
      

    Each object in the objects array follows the schema defined by objectSchema.

  5. Save the array instance to the database using the save method.
  6.     
        arrayInstance.save()
          .then(savedArray => {
            console.log(savedArray);
          })
          .catch(error => {
            console.error(error);
          });
        
      

    The save method returns a promise that resolves to the saved array instance if successful. You can handle any errors that occur during the saving process using the catch method.

    With this setup, you can now save an array of objects in Mongoose. Make sure to replace key1, key2, and any other keys with the actual keys you want to use in your objects.

Leave a comment