Useful plugin "findOrCreate" for Mongoose, which was coded in ES6.
npm install findorcreate-promise
!npm
!license
Useful mongoose plugin "findOrCreate-Promise", which was made using es6 Promises.
```
npm i findorcreate-promise
`javascript`
const import findOrCreate from 'findorcreate-promise';
First, we need to define a connection and add static method on the schema.
`javascript
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);
`
findOrCreate takes at most three arguments.
* query : The values to be searcheddata
* : 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.
`javascript`
Schema.findOrCreate({ query }, { data }, { options })
.then((doc) => {
/**
* doc.created is a boolean
* doc.result is an object
**/
})
.catch(done);
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.
`javascript`
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.
`javascript`
Test.findOrCreate({ name: 'mongoose' }, { password: 'nosql' })
.then((doc) => {
/**
* doc.created = true
* doc.result = new document
**/
})
.catch(done);
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.
`javascript`
Test.findOrCreate({ name: 'mongoose' }, { name: 'mongoDB' }, { upsert: true })
.then((doc) => {
/**
* doc.created = false
* doc.result = document update
**/
})
.catch(done);
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.
`javascript`
Test.findOrCreate({ name: 'mongoose' }, {}, { create: false })
.then((doc) => {
/**
* doc.created = false
* doc.result = null
**/
})
.catch(done);
* babel-core
* babel-eslint
* babel-preset-latest
* babel-preset-stage-2
* chai
* chai-as-promised
* eslint
* eslint-config-airbnb-base
* eslint-plugin-import
* mocha
* mongoose
```
npm test
When you find issues, please report them:
* web: https://github.com/ileghlam/findOrCreate/issues
* __MIT__: http://opensource.org/licenses/MIT