1

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 additional 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.

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.