我正在为我的前端应用程序使用mongoose,mongoDb和expressjs编写小型REST API。我有问题保存布尔数组对象。其他数组对象按预期保存在数据库中,但布尔值除了第一个数组值外,还得到意外的id而不是值。这是我的代码: 模型架构:
const companiesSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
benefitsOffers: [
{
balance : Boolean
},
{
car: Boolean
},
{
bonseModel: Boolean
},
{
centerlaOffice: Boolean
},
{
owenerShip: Boolean
},
]
})
module.exports = mongoose.model('Companies', companiesSchema);
Postman发送的测试值
{
"benefitsOffers": [
{
"balance": true
},
{
"car": false
},
{
"bonseModel": true
},
{
"centerlaOffice": true
},
{
"owenerShip": true
},
]
}
服务器响应
{
"_id": "5ad93a2bd60c32622a8fce1d",
"benefitsOffers": [
{
"_id": "5ad93a2bd60c32622a8fce34",
"balance": true
},
{
"_id": "5ad93a2bd60c32622a8fce33"
},
{
"_id": "5ad93a2bd60c32622a8fce32"
},
{
"_id": "5ad93a2bd60c32622a8fce31"
},
{
"_id": "5ad93a2bd60c32622a8fce30"
},
}
我有其他数据类型的类似数组结构,没有问题。我错过了什么? ,我引用了官方文档,它没有任何关于布尔数组对象的具体事情。我只是需要某人查明我的错误
答案 0 :(得分:0)
这是一个解决方案
创建 benefitsOffers
作为单独的架构
const benefitsOffersSchema = new Schema({
balance : { type : Boolean, default: false },
car : { type : Boolean, default: false },
bonseModel : { type : Boolean, default: false },
centerlaOffice : { type : Boolean, default: false },
owenerShip : { type : Boolean, default: false }
});
将 benefitsOffersSchema
附加到companiesSchema
const companiesSchema = mongoose.Schema({
benefitsOffers : [benefitsOffersSchema]
})
const Companies = mongoose.model("Companies",companiesSchema);
module.exports = Companies;
现在您可以插入布尔值
var benefitsOffers = {
balance : true,
car : true,
bonseModel : false,
centerlaOffice : false,
owenerShip : false
};
var company = new Companies({ benefitsOffers : benefitsOffers});
company.save();
下方是插入文档的输出