1.2.0 • Published 7 years ago

findorcreate-promise v1.2.0

Weekly downloads
114
License
MIT
Repository
github
Last release
7 years ago

findOrCreate-Promise

Build Status npm license

Useful mongoose plugin "findOrCreate-Promise", which was made using es6 Promises.

Installation

npm i findorcreate-promise

Import plugin

const import findOrCreate from 'findorcreate-promise';

Connecting to MongoDB

First, we need to define a connection and add static method on the schema.

const import mongoose from 'mongoose';
const Schema = mongoose.Schema;

const TestSchema = new Schema({
    name: { type: String },
    password: { type: String },
});

TestSchema.plugin(findOrCreate);

const Test = mongoose.model('Test', TestSchema);

Usage

Basic Usage

findOrCreate takes at most three arguments.

  • query : The values to be searched
  • data : If a document is created, these values will be defined.
  • options: Decides different behavior in the vent an object is found or created.

The function returns in all cases the object in question, whether it was found or created, and a boolean. The boolean is true if it created a new document and false if it found and or updated one.

Schema.findOrCreate({ query }, { data }, { options })
    .then((doc) => {
       /**
        * doc.created is a boolean
        * doc.result is an object
        **/
    })
    .catch(done);

Create or Find a new document

You can create a new document by searching for values. If a matching document is found, it is returned. Otherwise a new document with the searched values is created and returned.

Test.findOrCreate({ name: 'mongoose' })
    .then((doc) => {
       /**
        * doc.created = true
        * doc.result = new document
        **/
    })
    .catch(done);

You can create a new document by searching values and in the second parameter, define values in the new document.

Test.findOrCreate({ name: 'mongoose' }, { password: 'nosql' })
    .then((doc) => {
       /**
        * doc.created = true
        * doc.result = new document
        **/
    })
    .catch(done);

Update a document

The option upsert dictates how to handle found objects. If it is true, the values passed in data are updated in the object. By default it's false.

Test.findOrCreate({ name: 'mongoose' }, { name: 'mongoDB' }, { upsert: true })
    .then((doc) => {
       /**
        * doc.created = false
        * doc.result = document update
        **/
    })
    .catch(done);

Create option

An object is created by default if it is not found. However, if create is set to false, the function performs only a find and no new object will be created.

Test.findOrCreate({ name: 'mongoose' }, {}, { create: false })
    .then((doc) => {
       /**
        * doc.created = false
        * doc.result = null
        **/
    })
    .catch(done);

Dev Dependencies

Test

npm test

Bugs

When you find issues, please report them:

License