我想在mongodb上的单个文档中添加多个对象

时间:2019-03-29 12:46:05

标签: node.js mongodb mongoose

我的对象是

[ { Indicator: 'RA', Year: '2019' },
  { Indicator: 'RR', Year: '2019' },
  { Indicator: 'ROOM REV', Year: '2019' },
  { Indicator: 'F&B REV', Year: '2019' },
  { Indicator: 'TOTAL REV', Year: '2019' },
  { Indicator: 'ROOM PROFIT', Year: '2019' },
  { Indicator: 'F&B PROFIT', Year: '2019' },
  { Indicator: 'GOP', Year: '2019' },
  { Indicator: 'BASIC', Year: '2019' },
  { Indicator: 'TRAD', Year: '2019' },
  { Indicator: 'INC', Year: '2019' } ]

,我想将该对象添加到单个文档中。

Nodejs代码;

router.post('/api/sendJsonTable', function(req,res,next){
  var body = req.body
    console.log(body)
    Data.create(body, function (error, data) {
      if (error) {
        return next(error);
      } 
    });

})

模型

var DataSchema = new mongoose.Schema({
    value: {
        type: String,
        trim: true
    },
    indicator: {
        type: String,
        trim: true
    },

})

尝试该代码时,该代码将创建11个文档。

1 个答案:

答案 0 :(得分:0)

将架构更改为类似

var DataSchema = new mongoose.Schema({
    something : {
      value: {
        type: String,
        trim: true
      },
      indicator: {
        type: String,
        trim: true
      }
    }
})

或者您可以使用subdoc模式。