Jane
Jane

Reputation: 65

mongoDB/mongoose: Is it possible to modify _id when projecting `.find` results?

I tried "_id": "$field", but it doesn't work.

"_id": 0 removes the _id field entirely

Upvotes: 0

Views: 57

Answers (1)

Shubham
Shubham

Reputation: 1426

using mongoose

var UserSchema = new mongoose.Schema({
       //other fields
    },{
        minimize: false,
        toJSON: {  
            transform: function (doc, ret) {
                ret.newField= ret._id;
                delete ret._id;
            }
        }
    });

and query like model.find()

using aggregation

model.aggregate([
{
$match:{}
},
{
$project:{
 "newField":"$_id",
 "_id":0
}
}
])

Upvotes: 1

Related Questions