尝试将对象推入mongodb数组时发生错误

时间:2018-04-08 18:03:04

标签: node.js mongodb events mongoose

我在nodejs上使用mongoose(5.0.1)进行MongoDB操作,并且在尝试将对象推送到MongoDB数组时发生错误。这是代码:

 //quesObj and testTitle are sent from clientside
 // quesObj is just an ordinary javascript object

  io.sockets.on('connection', function(socket){
      socket.on('save question', function(quesObj, testTitle){   
        eventEmitter.emit('save question db', quesObj, testTitle);
      });
  });

  eventEmitter.on('save question db', function(quesObj, testTitle){
    testModel.findOne({'title': testTitle}, function(err, foundQues){
      foundQues.questions.push(quesObj)
      foundQues.save();
    });  
 });

这是推送操作行上发生的错误:

throw er; // Unhandled 'error' event      

TypeError: this._schema.caster.applySetters is not a function
at Array._cast (/home/mintx/testmate/testmate/node_modules/mongoose/lib/types/array.js:122:32)
at Array._mapCast (/home/mintx/testmate/testmate/node_modules/mongoose/lib/types/array.js:296:17)
at Arguments.map (<anonymous>)
at Array.push (/home/mintx/testmate/testmate/node_modules/mongoose/lib/types/array.js:310:25)
at /home/mintx/testmate/testmate/app.js:54:25
at model.Query.<anonymous> (/home/mintx/testmate/testmate/node_modules/mongoose/lib/model.js:3913:16)
at /home/mintx/testmate/testmate/node_modules/kareem/index.js:297:21
at /home/mintx/testmate/testmate/node_modules/kareem/index.js:135:16
at process._tickCallback (internal/process/next_tick.js:150:11)

这是我试图将对象推入的模型中的'questions'数组:

const testSchema = new Schema({
title: {
    type: String,
    unique: true
},
numberOfQuestions: Number,
questions: [Object]
});

1 个答案:

答案 0 :(得分:2)

您必须在questions

中为testSchema属性指定架构

你不应该简单地保持对象questions: [Object]

要修复您的代码,您需要

1.在您想要的任何结构中创建questionSchema,下面是questionSchema的示例结构

const questionsSchema =  new Schema({
    topic : {
        type : String
    }
});

2.在questionSchema

中添加questionstestSchema媒体资源
const testSchema = new Schema({
    title: {
        type: String,
        unique: true
    },
    numberOfQuestions: Number,
    questions: [questionSchema]
});

3.向questions属性 添加架构后(根据上面的示例,您必须添加的架构为questionSchema { {1}}可以使用