mongoose-findone-or-error
Simple Mongoose plugin for rejecting findOne and findById promises which resolve null.
Installation
Hook the plugin to a schema:
const mongoose = require('mongoose');
const findOrErrorPlugin = require('mongoose-findone-or-error');
mongoose.plugin(findOrErrorPlugin);
const mongoose = require('mongoose');
const findOrErrorPlugin = require('mongoose-findone-or-error');
const schema = new mongoose.Schema({
name: String,
description: String
});
schema.plugin(findOrErrorPlugin);
mongoose.model('Example', schema);
Usage
Execute use statics method
const Example = require('./example');
Example.findByIdOrError('idNotInDatabase')
.then(doc => {
console.log('Only executed when document is found');
})
.catch(err => {
console.log(err);
});
Example.findByIdOrError('idNotInDatabase', function(err, doc) {
if (err) {
console.log('Here not found error');
return
}
console.log('Only executed when document is found');
})
Example.findOneOrError({ name: 'plugin example' })
.then(doc => {
console.log('Only executed when document is found');
})
.catch(err => {
console.log(err);
});
Example.findOneOrError({ name: 'plugin example' }, function(err, doc) {
if (err) {
console.log('Here not found error');
return
}
console.log('Only executed when document is found');
})
Execute use query helpers:
const Example = require('./example');
Example.findOne({ name: 'plugin example' })
.select({name: 1})
.throwEmpty()
.limit(10)
.then(doc => {
console.log('Only executed when document is found');
})
.catch(err => {
console.log(err);
});
Example.findOne({
name: 'plugin example'
}, null, {
lean: true,
emptyError: true
})
.then(() => {
console.log('Only executed when document is found');
})
.catch(err => {
console.log(err);
});
Example.findOne({
name: 'plugin example'
}, '_id name', {
emptyError: true
}, function(err, doc) {
if (err) {
console.log('Here not found error');
return
}
console.log('Only executed when document is found');
})
...
Default Error Handle
function defaultSendEmptyError (modelName, query, emptyQueryOption) {
const error = new Error(`${_.upperFirst(_.camelCase(modelName))} not found.`)
error.name = 'DocumentNotFoundError'
if (!_.isBoolean(emptyQueryOption)) { error.code = emptyQueryOption }
return error
}
Plugin Options
schema.plugin(findOrErrorPlugin, {
static: {
findOneFname: 'findOneOrError',
findByIdFname: 'findByIdOrError'
},
query: {
queryFname: 'throwEmpty',
queryOption: 'emptyError'
},
sendEmptyError: sendEmptyError
});
Error With code
Example.findOne({ name: 'plugin example' })
.select({name: 1})
.throwEmpty(404)
.limit(10)
.then(doc => {
console.log('Only executed when document is found');
})
.catch(err => {
console.log(err.code)
});
Example.findOne({
name: 'plugin example'
}, '_id name', {
emptyError: 404
}, function(err, doc) {
if (err) {
console.log(err.code)
return
}
console.log('Only executed when document is found');
})
Running tests
npm test