Search code examples
node.jsmongodbexpressmongoosemongoose-schema

Mongoose schema structure


For the mongoose section does anyone knows difference between these two codes for defining Schemas?

const userSchema = new mongoose.Schema({
    userName : String,
    passWord : String
})

const userSchema = {
    userName : String,
    passWord : String
}

like using a JSON object directly instead of wrapping them inside the mongosse Schema function as parameters


Solution

  • The userSchema object returned by mongoose.Schema looks like this.

    {
      obj: { userName: [Function: String], passWord: [Function: String] },
      paths: {
        userName: SchemaString {
          enumValues: [],
          regExp: null,
          path: 'userName',
          instance: 'String',
          validators: [],
          getters: [],
          setters: [],
          _presplitPath: [Array],
          options: [SchemaStringOptions],
          _index: null,
          [Symbol(mongoose#schemaType)]: true
        },
        passWord: SchemaString {
          enumValues: [],
          regExp: null,
          path: 'passWord',
          instance: 'String',
          validators: [],
          getters: [],
          setters: [],
          _presplitPath: [Array],
          options: [SchemaStringOptions],
          _index: null,
          [Symbol(mongoose#schemaType)]: true
        },
        _id: ObjectId {
          path: '_id',
          instance: 'ObjectID',
          validators: [],
          getters: [],
          setters: [Array],
          _presplitPath: [Array],
          options: [SchemaObjectIdOptions],
          _index: null,
          defaultValue: [Function],
          [Symbol(mongoose#schemaType)]: true
        }
      },
      aliases: {},
      subpaths: {},
      virtuals: {},
      singleNestedPaths: {},
      nested: {},
      inherits: {},
      callQueue: [],
      _indexes: [],
      methods: {},
      methodOptions: {},
      statics: {},
      tree: {
        userName: [Function: String],
        passWord: [Function: String],
        _id: { auto: true, type: 'ObjectId' }
      },
      query: {},
      childSchemas: [],
      plugins: [],
      '$id': 1,
      mapPaths: [],
      s: { hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} } },
      _userProvidedOptions: {},
      options: {
        typePojoToMixed: true,
        typeKey: 'type',
        id: true,
        noVirtualId: false,
        _id: true,
        noId: false,
        validateBeforeSave: true,
        read: null,
        shardKey: null,
        autoIndex: null,
        minimize: true,
        discriminatorKey: '__t',
        optimisticConcurrency: false,
        versionKey: '__v',
        capped: false,
        bufferCommands: true,
        strictQuery: false,
        strict: true
      }
    }
    

    I hope you see the difference.