Home > OS >  How to avoid generating object id while creating subobject in array in mongoDb
How to avoid generating object id while creating subobject in array in mongoDb

Time:10-15

In my document i have array of images in which each image has url and public_id. I want only the url public_id but addditional parameter of _id is also stored. Which i want to avoid.

Stored in the database as:

"images": [
      {
        "url": "https://res.cloudinary.com/dpurb6xes/image/upload/v1665806337/vivans/po0zh7eots60azad3y5b.png",
        "public_id": "vivans/po0zh7eots60azad3y5b",
        "_id": "634a4db7177280021c56737c"
      },
      {
        "url": "https://res.cloudinary.com/dpurb6xes/image/upload/v1665806337/vivans/po0zh7eots60azad3y5b.png",
        "public_id": "vivans/po0zh7eots60azadasdb",
        "_id": "634a4db7177280021c56737d"
      }
    ],

Mongoose Schema

const imageArray = new mongoose.Schema({
url: { type: String },
public_id: { type: String },
});

const productSchema = new mongoose.Schema({
    images: [imageArray],
});

My Post request

{
"images": [
    {
      "url": "https://res.cloudinary.com/dpurb6xes/image/upload/v1665806337/vivans/po0zh7eots60azad3y5b.png",
      "public_id": "vivans/po0zh7eots60azad3y5b"
    },
    {
      "url": "https://res.cloudinary.com/dpurb6xes/image/upload/v1665806337/vivans/po0zh7eots60azad3y5b.png",
      "public_id": "vivans/po0zh7eots60azadasdb"
    }
  ],
}

How to get rid of _id stored in the database.

CodePudding user response:

Converting

const imageArray = new mongoose.Schema(
    {
        url: { type: String },
        public_id: { type: String },
    },
);

to

const imageArray = new mongoose.Schema(
    {
        url: { type: String },
        public_id: { type: String },
    },
    { _id: false }
);

Solved the problem.

CodePudding user response:

The Schema class can receive a second parameter, which is used to pass some options, one of them is "_id", which is a boolean value, so you just have to provide this second parameter with the _id property as false in order to avoid create the _id property in your documents.

This way:

const imageArray = new mongoose.Schema({
    url: { type: String },
    public_id: { type: String },
}, { _id: false }
);

You can look the entire options list in the official docs: Mongoose Schema - options

  • Related