Search code examples
node.jsmongodbmongoose

replace id with _id with toObject in mongoose node.js gets wrong


I am using mongoose and node.js, here is a simple schema

const addressSchema = new mongoose.Schema({

    address: String,
    region: String,
    fullArea: Array,

},{
  timestamps: true,
  versionKey: false,
  toObject: {
      virtuals: true,
      getters: true,
      transform: (_, ret) => {            
          ret.id = ret._id;
          delete ret._id;
      }
  },
})

I am using toObject() in order to return the data object with id instead of _id.

  const alls = await addressModel
    .find(query)
    .skip(skip)
    .limit(limit)
    .exec();

  console.log( alls );

when printing in the console in the server side, I see the data object has the id instead of _id.

  [
    {
      ....
      __v: 0,
      id: new ObjectId('6645b78ade005ba6ca47310e')
    }
  ]

but when the express server sends the same data back to the client, res.status(StatusCodes.OK).json( data );

the ultimate data received on the client side is always has _id not expected id

{
  "data":[
    { "_id":"6645b78ade005ba6ca47310e",....}
  ]
}

what happened ?


Solution

  • You need to use the toJSON helper instead:

    addressSchema.options.toJSON = {
        transform: function(doc, ret, options) {
            ret.id = ret._id;
            delete ret._id;
        }
    };