mongodb 中怎么新增数据?

定义好的 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 的错误,请问我应该怎么操作?
非常感谢!

阅读 2.4k
2 个回答

感觉是 Schema 设计有问题,如果去掉数组,就可以添加成功,类似这样:

const ProductCateogorySchema = new Schema({
      user:{
            type:Schema.Types.ObjectId,
            ref:"users"
      },
      product:[],
      cateogoryName:{
            type:String,
            required:true
      },
      cateogoryDes:{
            type:String
      },
      subTwoCateogory:[],
      subThreeCateogory:[],
      date:{
            type:Date,
            default:Date.now
      }
});
router.post('/cateogory/add',urlencodedParser,(req,res) => {
      const newFields = {
            cateogoryName: req.body.cateogoryOneName,
            cateogoryDes:req.body.cateogoryOneDes
      }
      
      new CateogoryOneSchema(newFields).save().then(cateogories => {
            res.redirect('/product/cateogory');
            res.send(cateogories);
      }).catch(err => {
            console.log(err)
      });
})
这样就可以添加成功,但是如果存在数组,从数据库中就读取不到数组,然后一直添加失败。
  1. 检查有没有成功连接数据库
  2. save是异步操作,返回操作应该在save的回调或者在promise.then里
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进