Home > Net >  Mongoose _id changes on every request
Mongoose _id changes on every request

Time:11-04

So, I am building an application using MongoDB as my Database. In my database exist 3 different schemas: Section, Category, and Product.

The schemas are defined as follows:

let ProductSchema = new mongoose.Schema({
    name: String,
    price: String,
    imageLink: String
})

let CategorySchema = new mongoose.Schema({
    name: String,
    products: [{ ref: 'Product', type: mongoose.Types.ObjectId}],
    link: String
})

let SectionSchema = new mongoose.Schema({
    name: String,
    categories: [{ ref: 'Category', type: mongoose.Types.ObjectId }]
})

Then I have built a simple API, using Express, to test the integration, and when retrieving all the Sections, Categorys and Products using the find()method on their respective models, the _ids of the objects change. So, for example, for a simple query for a Section with its _idI get the following result:

{
    "_id": "618042725b8fc016e4b76714",
    "name": "AHUMADOS Y CAVIAR",
    "categories": [
        {
            "_id": "61804dee7ac1146082cdb4b2",
            "products": []
        }
    ],
    "__v": 0
}

Then I make the same request once again and I get the following:

{
    "_id": "618042725b8fc016e4b76714",
    "name": "AHUMADOS Y CAVIAR",
    "categories": [
        {
            "_id": "61804e257ac1146082cdb4b6",
            "products": []
        }
    ],
    "__v": 0
}

As you can see the _id of the objects inside categories change on every query, which is a weird behaviour. Does anybody know why this is happening?

Thank your in advance for your answers.

CodePudding user response:

I have the code for creating the database model in a one project, and the code for accessing the database in another one. The thing is that the schemas used for creating the database were the ones posted in the original question, but the ones used for accessing the database where the following:

let ProductSchema = new mongoose.Schema({
    name: String,
    price: String,
    imageLink: String
})


let CategorySchema = new mongoose.Schema({
    name: String,
    products: [ProductSchema],
    link: String
})

let SectionSchema = new mongoose.Schema({
    name: String,
    id: Number,
    categories: [CategorySchema]
})

So, I guess, that when using those schemas to query the database, mongoose was creating a new model object for each one of them, resulting in the _id changing all the time.

Simply changing the code for the schemas used for accessing the database and replacing them for the correct ones, solved the issue.

  • Related