Search code examples
javascriptnode.jsmongodbexpressmongoose

What is the right way to store an array of objects in MongoDB using Mongoose?


Language: Javascript, Environment: Node JS, Framework: Express & Library: Mongoose

I was working on an application where I needed to store some data in a mongoDB document in the form of an array of objects?

There are two different ways to do this once I searched the internet.

  1. Create another sub-schema
const mongoose = require('mongoose');
const subSchema = new mongoose.Schema({
    name: String,
    age: Number
});

const schema = new mongoose.Schema({
    details: [subSchema]
});

const model = mongoose.model('Model', schema);
  1. Create a nested object
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
    details: [{
        name: String,
        age: Number
    }]
});

Now, which one is the right method and should be used? Also, are there any hidden strings to this?

PS:

I am using the second method and while storing the data, each object inside details is having a separate ObjectID with it. Is this the difference?


Solution

  • Because your question is what are the differences between the two approaches, I found a helpful explanation by mongoose:

    https://mongoosejs.com/docs/subdocs.html#subdocuments-versus-nested-paths