A plugin that adds an upsertMany bulk op to Mongoose schemas
You can install this package using yarn
or npm
.
#yarn
yarn add @meanie/mongoose-upsert-many
#npm
npm install @meanie/mongoose-upsert-many --save
Setup as a global plugin for all Mongoose schema's:
const mongoose = require('mongoose');
const upsertMany = require('@meanie/mongoose-upsert-many');
mongoose.plugin(upsertMany);
Or for a specific (sub) schema:
const mongoose = require('mongoose');
const upsertMany = require('@meanie/mongoose-upsert-many');
const {Schema} = mongoose;
const MySchema = new Schema({});
MySchema.plugin(upsertMany);
This plugin will expose a static upsertMany
method on your models which you
can use to perform bulk upsert operations:
//Large amount of items
const items = [
...
];
//Fields to match on for upsert condition
const matchFields = ['foo', 'bar.nested'];
//Perform bulk operation
const result = await MyModel.upsertMany(items, matchFields);
//Returns promise with MongoDB bulk result object
console.log(result.nUpserted + result.nModified, 'items processed');
Items you pass in can be mongoose Models or raw data, but they are always converted to Mongoose models to ensure schema validation is applied, and then converted back to plain, depopulated objects for safe insertion with the bulk operation.
Match fields are fields that are used as match criteria for the upsert operations,
e.g. in the find()
portion of the bulk op. You can also provide default match
fields for the whole schema using the option upsertMatchFields
when defining your schema.
Please report any bugs, issues, suggestions and feature requests in the @meanie/mongoose-upsert-many issue tracker.
Pull requests are welcome! If you would like to contribute to Meanie, please check out the Meanie contributing guidelines.
This package has been kindly sponsored by Hello Club, an all in one club and membership management solution complete with booking system, automated membership renewals, online payments and integrated access and light control. Check us out if you happen to belong to any kind of club or if you know someone who helps run a club!
(MIT License)
Copyright 2018-2020, Adam Reis