Mongoose query: remove "_id" attribute, keep virtual attribute "id" in results

If you are using mongoose,

You can handle in when toJSON, you can decide how it display but you can't mention it in your query.

Model.find().select('name').exec(function(err,model) {}

 new mongoose.Schema(yourSchema, {
    toJSON: { 
       transform: function(doc, ret) {
         ret.id = ret._id;
         delete ret._id;
       }
     }
   );}

You might use global approach. Try this one out:

mongoose.plugin((schema) => {
  schema.options.toJSON = {
    virtuals: true,
    versionKey: false,
    transform(doc, ret) {
      ret.id = ret._id;
      delete ret._id;
    }
  };
});

You cannot do that. MongoDB requires _id attribute to be present as per documentation.

Your option is to use virtual attribute as in your example and perhaps $project to hide the field in the query result.

Otherwise, your mongo driver, such as Mongoose, should be able to hide or rename the desired field or attribute.