代码之家  ›  专栏  ›  技术社区  ›  Recusiwe

尝试推送时Mongoose数组为空

  •  0
  • Recusiwe  · 技术社区  · 7 年前

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

    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 回复  |  直到 7 年前
        1
  •  0
  •   Jitendra    7 年前

    不需要像那样寻找和推送答案。您可以通过使用直接搜索和推送您的答案 $push 在mongodb。详情如下:

    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)
    
    }
    
    推荐文章