meteor How to use upsert | Exception while simulating the effect of invoking ” TypeError: Cannot read properties of undefined (reading ‘_id’) react.js

meteor How to use upsert | Exception while simulating the effect of invoking ” TypeError: Cannot read properties of undefined (reading ‘_id’) react.js

我在使用 upsert 和 meteor.js 时遇到问题。我可以使用以下代码很好地更新问题,但我将无法插入新数据。

客户端文件

const onSave = () =>{
       // there is  more codes but omitted
     questions.forEach(question => {
     Meteor.call('modifyQuestion', question);
 })
}

服务器端的文件(集合文件)

  modifyQuestion(question) {
    check(question, Object);

    const questionId = Measures.findOne({questionId: question._id});
    Measures.upsert(
      {_id: questionId._id},
      {
        $set: {
          title: question.text,
        },
      },
    );
  },

收到错误提示... Exception while simulating the effect of invoking 'modifyQuestion' TypeError: Cannot read properties of undefined (reading '_id')

我想当 {_id: questionId._id} 未定义时,那是时候 upsert 明白没有找到匹配的数据并将一个作为新数据插入数据库。 这有错吗?

我把$set换成了$setOnInsert,还是不行...

已添加

现在我没有看到任何错误,但我无法插入新数据。我可以更新数据。

  modifyQuestion(question) {
    check(question, Object);
    
    Measures.upsert(
      {questionId: question._id}, // changed
      {
        $set: {
          title: question.text,
        },
        $setOnInsert: {type: 'multipleChoice'}
      },
    );
  },

还删除了 const questionId = Measures..... 部分

您仍然需要在插入时设置 questionId

  modifyQuestion(question) {
    check(question, Object);
    
    Measures.upsert(
      { questionId: question._id },
      {
        $set: {
          title: question.text,
        },
        $setOnInsert: {
          questionId: question._id
          type: 'multipleChoice'
        }
      },
    );
  },

否则将永远不会有包含 questionId.

的文档

注意:另一个有用的工具是 Collection2 并定义模式,因此它会抛出错误,以防文档 inserted/updated 违反模式。使用这个会抛出,插入时缺少 questionId