22

私のスキーマをこのように定義しているようです:

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

またはこの方法:

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

どちらも機能します。マングース ガイドが Schema.Types.ObjectId を使用していることがわかります

http://mongoosejs.com/docs/schematypes.html

しかし、私は両方が機能することに混乱しています。

スキーマにはどれを使用する必要がありますか? そして、2つの違いは何ですか?

4

4 に答える 4

13

それは問題ではありません。どちらもまったく同じです。実際にconsole.log(mongoose.Schema);両方を見て、まったく同じことを参照できるmongoose.Schema.ObjectId場合mongoose.Schema.Types.ObjectId

{ [Function: Schema]
  reserved: { 
    _posts: 1,
    _pres: 1,
    validate: 1,
    toObject: 1,
    set: 1,
    schema: 1,
    save: 1,
    modelName: 1,
    get: 1,
    isNew: 1,
    isModified: 1,
    init: 1,
    errors: 1,
    db: 1,
    collection: 1,
    once: 1,
    on: 1,
    emit: 1 
  },
  interpretAsType: [Function],
  Types: { 
    String: { [Function: SchemaString] schemaName: 'String' },
    Number: { [Function: SchemaNumber] schemaName: 'Number' },
    Boolean: { [Function: SchemaBoolean] schemaName: 'Boolean', '$conditionalHandlers': [Object] },
    DocumentArray: { [Function: DocumentArray] schemaName: 'DocumentArray' },
     Embedded: [Function: Embedded],
    Array: { [Function: SchemaArray] schemaName: 'Array' },
    Buffer: { [Function: SchemaBuffer] schemaName: 'Buffer' },
    Date: { [Function: SchemaDate] schemaName: 'Date' },
    ObjectId: { [Function: ObjectId] schemaName: 'ObjectId' },
    Mixed: { [Function: Mixed] schemaName: 'Mixed' },
    Oid: { [Function: ObjectId] schemaName: 'ObjectId' },
    Object: { [Function: Mixed] schemaName: 'Mixed' },
    Bool: { [Function: SchemaBoolean] schemaName: 'Boolean', '$conditionalHandlers': [Object] } 
  },
  ObjectId: { [Function: ObjectId] schemaName: 'ObjectId' } 
}
于 2015-11-12T09:50:19.713 に答える
7

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)
}
于 2018-09-28T20:15:05.667 に答える