I’m having trouble with upsert with meteor.js. I could update questions finely with the below codes but I won’t be able to insert new data.

file in client side

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

file in server side (collection file)

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

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

Got error saying… Exception while simulating the effect of invoking 'modifyQuestion' TypeError: Cannot read properties of undefined (reading '_id')

I thought when {_id: questionId._id} got undefined, that’s the time upsert understand that there is no matching data found and insert one as new data into the database. Is this wrong?

I switched $set to $setOnInsert, but still didn't work...

ADDED

Now I don't see any error but i couldn't insert new data. I could update data tho.

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

Also removed const questionId = Measures..... part

1

There are 1 answers

0
Jankapunkt On BEST ANSWER

You still need to set the questionId on insert:

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

Otherwise there will never be a doc that contains the questionId.

Note: Another helpful tool would be Collection2 and define a schema, so it throws errors, in case docs are inserted/updated that violate a schema. Using this would have thrown, that questionId is missing on insert.