定义好的 Schema 中有一个数组 cateogoryList:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProductCateogorySchema = new Schema({
user:{
type:Schema.Types.ObjectId,
ref:"users"
},
cateogoryList:[
{
cateogoryName:{
type:String,
required:true
},
cateogoryDes:{
type:String
}
},
{
cateogorySubList:[
]
}
],
date:{
type:Date,
default:Date.now
}
});
module.exports = mongoose.model('cateogories',ProductCateogorySchema);
现在是通过表单往这个数组中添加数据。正常情况下,是要先从这个Schema 中查询,找到这个cateogoryList后,再添加数据,最后保存,但是我这里碰到这样一个问题:
对查询到Schema 中的这个cateogoryList数组,无法操作它,也可能是我不知道怎么操作它,然后就没办法写入数据。
正面是这个POST的方法:
router.post('/cateogory/add',urlencodedParser,(req,res) => {
CateogoryOneSchema.find().then(cateogory => {
if(!cateogory){
console.log('cateogory :' + cateogory)
const newFields = {
cateogoryName: req.body.cateogoryOneName,
cateogoryDes:req.body.cateogoryOneDes
}
const category = {};
category.categoryList = [];
category.categoryList.push(newFields);
cateogory.save();
}
})
})
打印到的 cateogory 为刚插入不成功的空数据:
但是当使用 category.categoryList 就会报一个不能使用 push 的错误,请问我应该怎么操作?
非常感谢!
感觉是 Schema 设计有问题,如果去掉数组,就可以添加成功,类似这样: