To save an array of objects in Mongoose, you can follow these steps:
- Define a schema for the objects in the array using Mongoose’s
Schema
class. - Create an instance of the
ArrayModel
and populate the objects array with the desired data. - Save the array instance to the database using the
save
method.
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.
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
.
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.