cod*_*ior 22 mongoose mongodb mongodb-query
我正在定义一个mongoose模式,定义如下:
inventoryDetails: {
type: Object,
required: true
},
isActive:{
type:Boolean,
default:false
}
Run Code Online (Sandbox Code Playgroud)
我尝试了"对象"类型,我看到我的数据已成功保存.当我将类型更改为数组时,保存失败.
样本数据:
{
"inventoryDetails" : {
"config" : {
"count" : {
"static" : { "value" : "123" },
"dataSource" : "STATIC"
},
"title" : {
"static" : { "value" : "tik" },
"dataSource" : "STATIC"
}
},
"type" : "s-card-with-title-count"
}
}
Run Code Online (Sandbox Code Playgroud)
"对象"类型不是猫鼬允许的类型之一.但是,如何支持它?
Jus*_*tin 41
你有两个选择来进入你Object的数据库:
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
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
看看我的真实代码:
let UserSchema = new Schema({
//...
statuses: {
online: {
type: Boolean,
default: true
},
verified: {
type: Boolean,
default: false
},
banned: {
type: Boolean,
default: false
}
},
//...
})
Run Code Online (Sandbox Code Playgroud)
此选项使您能够定义对象的数据结构.
如果需要灵活的对象数据结构,请参阅下一个.
Schema.Types.Mixed类型从doc获取的示例:
let YourSchema = new Schema({
inventoryDetails: Schema.Types.Mixed
})
let yourSchema = new YourSchema;
yourSchema.inventoryDetails = { any: { thing: 'you want' } }
yourSchema.save()
Run Code Online (Sandbox Code Playgroud)
猫鼬 5
“一切皆有可能”的 SchemaType。Mongoose 不会在混合路径上进行任何投射。您可以使用Schema.Types.Mixed或通过传递空对象文字来定义混合路径。以下是等效的。
const Any = new Schema({ any: {} });
const Any = new Schema({ any: Object });
const Any = new Schema({ any: Schema.Types.Mixed });
const Any = new Schema({ any: mongoose.Mixed });
Run Code Online (Sandbox Code Playgroud)
对于您当前的架构,您可以使用下一个示例:
import mongoose from 'mongoose'
const inventorySchema = mongoose.Schema({
inventoryDetails: {
type: mongoose.SchemaTypes.Mixed,
required: true
},
isActive:{
type: Boolean,
default:false
}
})
const inventory = await inventorySchema.create({
inventoryDetails: {
config: {
count: {
static: { value: '123' },
dataSource: 'STATIC'
},
title: {
static: { value: 'tik' },
dataSource: 'STATIC'
}
},
type: 's-card-with-title-count'
}
})
console.log(inventory)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27786 次 |
| 最近记录: |