猫鼬模式结构

时间:2021-07-12 11:50:19

标签: node.js mongodb express mongoose mongoose-schema

对于 mongoose 部分,有人知道这两个定义 Schema 的代码之间的区别吗?

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

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

喜欢直接使用 JSON 对象,而不是将它们包装在 mongosse Schema 函数中作为参数

2 个答案:

答案 0 :(得分:0)

  import mongoose from 'mongoose';
  const { Schema } = mongoose;

  let blogSchema = new Schema({
    title:  String, // String is shorthand for {type: String}
    author: String,
  });
  
  //OR
  let blogSchema = new mongoose.Schema({
    title:  String, // String is shorthand for {type: String}
    author: String,
  });

是定义架构的正确方法。

答案 1 :(得分:0)

mongoose.Schema 返回的 userSchema 对象如下所示。

{
  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
  }
}

我希望你能看到不同之处。