Should I Use Schema.Types.ObjectId or Schema.ObjectId When Defining a Mongoose Schema

前端 未结 4 742
温柔的废话
温柔的废话 2021-02-12 23:39

It seems like defining my Schema this way:

var PossessionSchema = new mongoose.Schema({
  thing: {type: mongoose.Schema.Types.ObjectId, ref:\"Thing\"}
});
         


        
4条回答
  •  粉色の甜心
    2021-02-13 00:13

    I know this is an old topic but I ran into some trouble in this area recently, so here's what I found in case anyone else's banging their heads against the wall:

    Whenever you use a reference in your schema to an ObjectId, you MUST use mongoose.Schema.Types.ObjectId.

    mongoose.Types.ObjectId should be used solely for its constructor when building new objectIds from a string hex or, as it's probably the most common use case, to validate a string as an ObjectId hex, say:

    try {
      let oid = new mongoose.Types.ObjectId('XXXXXXXXX')
    } catch (e) {
      console.error('not a valid ObjectId hex string ==> ', e)
    }
    

提交回复
热议问题