Skip to content

A plugin that adds an upsertMany bulk op to Mongoose schemas

Notifications You must be signed in to change notification settings

raydaim/mongoose-upsert-many

 
 

Repository files navigation

@meanie/mongoose-upsert-many

npm version node dependencies github issues

A plugin that adds an upsertMany bulk op to Mongoose schemas

Meanie

Installation

You can install this package using yarn or npm.

#yarn
yarn add @meanie/mongoose-upsert-many

#npm
npm install @meanie/mongoose-upsert-many --save

Usage

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.

Issues & feature requests

Please report any bugs, issues, suggestions and feature requests in the @meanie/mongoose-upsert-many issue tracker.

Contributing

Pull requests are welcome! If you would like to contribute to Meanie, please check out the Meanie contributing guidelines.

Sponsor

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!

License

(MIT License)

Copyright 2018-2020, Adam Reis

About

A plugin that adds an upsertMany bulk op to Mongoose schemas

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%