尝试推送时,猫鼬数组为null

时间:2018-12-15 20:58:41

标签: node.js mongodb mongoose

我在玩猫鼬,并且得到了以下模式:

var connection = mongoose.createConnection(remoteDbUrl);

autoIncrement.initialize(connection);

var AnswerSchema = new mongoose.Schema({
  author: {
    type: String,
    required: [true, 'Author is required']
  },
  description: String,
  createdAt: { 
    type: Date, 
    default: Date.now 
  },
  votes: Number
}, {timestamps: true});

module.exports = Answer = mongoose.model('Answer', AnswerSchema);

var QuestionSchema = new mongoose.Schema({
  _id: Number,
  author: {
    type: String,
    required: [true, 'Author is required']
  },
  headline: String,
  description: String,
  answers: [AnswerSchema],
  createdAt: { 
    type: Date, 
    default: Date.now 
  }
}, {timestamps: true});

QuestionSchema.plugin(autoIncrement.plugin, 'Question');
module.exports = Question = mongoose.model('Question', QuestionSchema);

在我的数据库中,它看起来像这样:

enter image description here

以这种方式插入我的问题后:

const question1 = new Question({
      author: 'TestAuthor',
      headline: 'TestHeadline',
      description: 'TestDescription',
      answers: []
    }
  );

  question1.save().then(result => {
    console.log("Created");
    };
  );

看起来一切都很好,但是当我尝试推送到数组时,随着答案开始流动,我尝试像这样添加它们:

async function addAnswer(questionId, author, description) {
    const question = await Question.findById(questionId);

    const answer = new Answer({
      author: author,
      description: description
    });

    question.answers.push(answer);
    question.save();
}

我得到UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'answers' of null。我想念什么?

1 个答案:

答案 0 :(得分:0)

无需查找和推送这样的答案。您可以在mongodb中使用UserScriptExecuted.jpg直接搜索并推送答案。如下:

async function addAnswer(questionId, author, description) {

    const answer = new Answer({
      author: author,
      description: description
    });

    const question = await Question.findOneAndUpdate(
       { _id: questionId },
       {
          $push: {    
            answers: answer         // Bold Part will be your answer object
          }
       },
       {new: true }                 // To get the updated results in return            
     ).exec()

     console.log('Updated question document: ',question)

}