Dan Tang
Dan Tang

Reputation: 1333

Creating multiple documents in mongoose only if it does not currently exist

I was wondering if to create multiple documents in mongoose, but only if they do not exist currently? From the documentation, I've found the code below to create multiple documents, but just wondering how to ensure that it does not create a document if it currently exist?

In particular, if one document already exists, I would like the other documents that are not currently created to be created (rather than the entire create operation to fail).

From Documentation
var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.create(array, function (err, jellybean, snickers) {
  if (err) // ...
});

Upvotes: 3

Views: 4968

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151092

As noted in the documentation, the .create() method is a shortcut function for creating a new document for the given model and "saving" it to the collection. This actually works like the more formal .save() method but in shortcut form.

What you are describing though is more akin to the "upsert" behavior of the MongoDB .update() method. Which can also apply to its .findAndModify cousin or specifically in mongoose, the .findOneAndUpdate() method.

So with some sample code:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/nodetest');

var candySchema = new Schema({
  type: String
});

var Candy = mongoose.model( "Candy", candySchema );

var array = [
  { type: 'jelly bean' },
  { type: 'snickers' },
  { type: 'mars' },
  { type: 'snickers' }
];

array.forEach(function(n) {

  Candy.findOneAndUpdate( n, n, { upsert: true }, function(err,doc) {
    console.log( doc );
  });

});

You would see the following output:

{ _id: 535088e2e4beaab004e6cd97, type: 'jelly bean' }
{ _id: 535088e2e4beaab004e6cd98, type: 'snickers' }
{ _id: 535088e2e4beaab004e6cd99, type: 'mars' }
{ _id: 535088e2e4beaab004e6cd98, type: 'snickers' }

Noting that the second entry for 'snickers' actually refers to the object that was already created.

So that is a basic way to ensure that you are not actually creating the same data twice as long as you specify the "key" to match in the query condition.

Upvotes: 5

Related Questions