Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
916 views
in Technique[技术] by (71.8m points)

mongoose - How to create record if it does not exist in mongodb during bulkWrite?

The server will receiving lots of data. And issue is that I need to create records if a field name of the record does not exist in the database.

I am using mongoose for performing operations with mongodb.

db.getDb(async function (error, db) {
        await db._models.Model.bulkWrite(
          values.map((value) => {
            const instance = new db._models.Model({
              __v: 0,
            });
            return {
              updateOne: {
                filter: {
                  title: value,
                  _datasetId: dataset._id,
                },
                update: {
                  $set: {
                    _id: instance._id,
                    _datasetId: dataset._id,
                    title: tag,
                    createdBy: user._id,
                    createdAt: date,
                    updatedAt: date,
                    __v: instance.__v,
                  },
                },
                upsert: true,
              },
            };
          })
        );

I do not want to update existing record, but to create record if it does not exist. (If record with title and _datasetId exist, it should skip the values).

How can I achieve this?

question from:https://stackoverflow.com/questions/65851949/how-to-create-record-if-it-does-not-exist-in-mongodb-during-bulkwrite

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have already set upsert:true , in case updateOne do not find the document specified by the filter it will perform insert instead of update...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...