mongodb 猫鼬中的对象类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42019679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:53:55  来源:igfitidea点击:

Object type in mongoose

mongodbmongoosemongodb-query

提问by codewarrior

I am defining a mongoose schema and definition is as follows:

我正在定义一个猫鼬模式,定义如下:

   inventoryDetails: {
        type: Object,
        required: true

    },
    isActive:{
        type:Boolean,
        default:false
    }

I tried "Object" type and I am seeing my data is getting saved successfully. When I changed type to array, the save is failing.

我尝试了“对象”类型,我看到我的数据被成功保存。当我将类型更改为数组时,保存失败。

Sample Data:

样本数据:

{
    "inventoryDetails" : { 
        "config" : { 
            "count" : { 
                "static" : { "value" : "123" }, 
                "dataSource" : "STATIC" 
            }, 
            "title" : { 
                "static" : { "value" : "tik" }, 
                "dataSource" : "STATIC" 
            } 
        }, 
        "type" : "s-card-with-title-count" 
    } 
}

"Object" type is not one of the types that mongoose allows. But, how it is being supported ?

“对象”类型不是猫鼬允许的类型之一。但是,它是如何得到支持的?

回答by Justin

You have two options to get your Objectin the db:

您有两种选择可以进入Object数据库:

1. Define it by yourself

1.自己定义

let YourSchema = new Schema({
  inventoryDetails: {
    config: {
      count: {
        static: {
          value: {
            type: Number,
            default: 0
          },
          dataSource: {
            type: String
          }
        }
      }
    },
    myType: {
      type: String
    }
  },
  title: {
    static: {
      value: {
        type: Number,
        default: 0
      },
      dataSource: {
        type: String
      }
    }
  }
})

Take a look at my real code:

看看我的真实代码:

let UserSchema = new Schema({
  //...
  statuses: {
    online: {
      type: Boolean,
      default: true
    },
    verified: {
      type: Boolean,
      default: false
    },
    banned: {
      type: Boolean,
      default: false
    }
  },
  //...
})

This option gives you the ability to define the object's data structure.

此选项使您能够定义对象的数据结构。

If you want a flexible object data structure, see the next one.

如果您想要灵活的对象数据结构,请参阅下一个。

2. Use the default Schema.Types.Mixedtype

2.使用默认Schema.Types.Mixed类型

Example taken from the doc:

文档中获取的示例:

let YourSchema = new Schema({
  inventoryDetails: Schema.Types.Mixed
})

let yourSchema = new YourSchema;

yourSchema.inventoryDetails = { any: { thing: 'you want' } }

yourSchema.save()