mongoose (mongodb) Alias _id field

前端 未结 2 410
渐次进展
渐次进展 2020-12-18 19:29

Is it possible with mongoose use a different name, in my case uppercase \'ID\', as an alias for the schema _id field? Would I need to add a virtual or is there another way o

相关标签:
2条回答
  • 2020-12-18 19:41

    The easiest way is to specify alias in the schema:

    let s = new Schema({
        _id: { type: String, alias: "ID" }
    });
    

    This automatically creates both getter and setter, so it is possible to use ID everywhere instead of _id.

    Mongoose documentation on aliases

    0 讨论(0)
  • 2020-12-18 20:01

    You would use a virtual attribute for that. As in:

    yourSchema.virtual('ID').get(function() { return this._id; });
    
    0 讨论(0)
提交回复
热议问题