Home > database >  Mongodb update and insert data at the same time | upsert, react.js, meteor.js
Mongodb update and insert data at the same time | upsert, react.js, meteor.js

Time:04-28

I'm trying to update questions if the questions already exist, and insert new questions if a user adds new questions.

const onSave = () => {
    if (creating) {
      // ・・ when you create a new questions, this runs
    } else if (editing) {
      // when you edit questions, this runs
      questions.forEach((question) => {
        Measures.update(
          { _id: question._id },
          {
            $set: {
              title: question.text,
              type:
                question.type === QuestionType.SHORT_ANSWER
                  ? MeasureType.TEXT
                  : MeasureType.MULTIPLE_CHOICE,
              typeOptions: { frequency },
              shortCodeOptions: {},
              entity: System.getCurrentEntity()
            }
          }
        );
      });
    }
};

Right now, I just Measures.update() to update questions. But I would like to not only update but also insert new questions into Measures collection if they are just added.

I looked the mongodb document upsert but need a little more help. https://www.mongodb.com/docs/drivers/node/current/fundamentals/crud/write-operations/upsert/

I tried this but got an error saying "Mesures.updateMany() is not a function"

  Measures.updateMany(
    {_id: question._id},
    {
      $set: {
        title: question.text,
        type:
          question.type === QuestionType.SHORT_ANSWER
            ? MeasureType.TEXT
            : MeasureType.MULTIPLE_CHOICE,
        typeOptions: {frequency},
        shortCodeOptions: {},
        entity: System.getCurrentEntity(),
      },
    },
   {upsert: true},
  );

mongodb version 5.0.6

CodePudding user response:

You are looking at the wrong documentation. Meteor collections are not mongodb-driver collections. You want to use https://docs.meteor.com/api/collections.html#Mongo-Collection-upsert, i.e., just replace update with upsert (no options required).

  • Related