Home > front end >  How do I project id as something else with mongoose?
How do I project id as something else with mongoose?

Time:02-01

In my Node.js microservice, I use Mongoose to get a document out from my mongoDB. The document has many properties but i only want to project 3 of them:

I want to project the '_id' as 'id', then I want to project the 'name' and 'description'. I try to do it like this:

const group = await Groups.findOne(
    { 'orgId': Number(orgId), '_id': mongoose.Types.ObjectId(id) },
    {'id': '$_id', 'name': 1, 'description': 1}
);

But this is what it returns:

{
    "_id": "63c006b7f1f085f7d8a683ff",
    "name": "TestGroup",
    "description": "some description"
    "id": "63c006b7f1f085f7d8a683ff"
}

CodePudding user response:

If you just want to remove _id from your JSON output you can do this:

new mongoose.Schema(modelSchema, {
    toJSON: { 
       virtuals: true,
       transform: (doc, ret) => { delete ret._id; }
    }
});
  • Related