Using UUIDs in mongoose for ObjectID references

后端 未结 1 1738
余生分开走
余生分开走 2020-12-28 17:07

I\'m building a CRUD-style REST service with Node.js, Express and MongoDB using mongoose. This service is going to allow users of an already existing android application to

相关标签:
1条回答
  • 2020-12-28 17:29

    You can still use populate() with _id values of types besides ObjectID, but you do need to use the same type in the reference definition.

    So your trackPassSchema would need to change to:

    var trackPassSchema = new Schema({
        _id: { type: String, default: function genUUID() {
            return uuid.v1()
        }},
        vehicle: [
            {type: String, required: true, ref: 'Vehicle'}
        ]
    });
    

    As Adam notes in the comments, you could simplify your default value to:

    var trackPassSchema = new Schema({
        _id: { type: String, default: uuid.v1 },
        vehicle: [
            {type: String, required: true, ref: 'Vehicle'}
        ]
    });
    
    0 讨论(0)
提交回复
热议问题