getting schema attributes from Mongoose Model

后端 未结 9 1814
时光说笑
时光说笑 2020-12-01 06:19

I\'m using Mongoose.js to create models with schemas.

I have a list of models (many) and at times I\'d like to get the attributes/keys that make up a particular mo

相关标签:
9条回答
  • 2020-12-01 06:42

    The accepted answer did not work for me. But using Mongoose 5.4.2 I was able to get the keys by doing the following:

    const mySchema = new Schema({ ... });
    
    const arrayOfKeys = Object.keys(mySchema.obj);
    

    I'm using typescript, however. That might have been the problem.

    0 讨论(0)
  • 2020-12-01 06:46

    My solution uses mongoose model.

    Schema attributes

    const schema = {
      email: {
        type: String,
        required: 'email is required',
      },
      password: {
        type: String,
        required: 'password is required',
      },
    };
    

    Schema

    const FooSchema = new Schema(schema);
    

    Model

    const FooModel = model('Foo', FooSchema);
    

    Get attributes from model:

    Object.keys(FooModel.schema.tree)
    

    Result:

    [
      'email',
      'password',
      '_id',
      '__v'
    ] 
    
    0 讨论(0)
  • 2020-12-01 06:46

    If you want to have only the attributes you added and not the add methods by the ORM that starts with '$___', you have to turn the document into object then access the attributes like this:

    Object.keys(document.toObject());
    
    0 讨论(0)
提交回复
热议问题