Creating a Mongoose plugin that supports callbacks AND promises - node.js

I have a Mongoose plugin that currently only supports callbacks, I plan on possibly publishing it to npmjs, but I first wanted to make sure that it works just like the existing Mongoose functions/methods, which support callbacks and some built in promises, and you can also specify your own promise library.
I wanted to know what the best way was to implement the same functionality in my library, meaning how can I support both callbacks and promises? I found a similar SO thread, but thats specific to bluebird, which even though I like to use, Id like to not assume it will be used. (Also, that article looks like it might be out-dated, as I couldnt find nodeify in the bluebird api docs
I was thinking I could just do some basic logic to see if a function was provided as one of the parameters, if so, then execute the callback, if not, then return a promise... but im sure theres an easier way to do that.
Also, for the Promises, when I do return a promise, should I use the Promise thats inside the Mongoose object thats handed to the plugins? Meaning:
module.exports = Mongoose => {
// Just verifying, should I use this?..
const Promise = Mongoose.Promise
return Mongoose.model( 'Foobar', new Mongoose.Schema({ /* ... */ }) )
}
Update
Regarding the last question, about what Promise object to reference when returning promises, I tried using the Mongoose.Promise as stated above, code below:
module.exports = Mongoose => {
const Promise = Mongoose.Promise
const Schema = Mongoose.Schema
const fooSchema = new Schema({
name: Schema.Types.String
})
fooSchema.statics.blah = function( ) {
// Return Mongoose.Promise
return new Promise( ( res, rej ) => {
res( 'test' )
})
}
return Mongoose.model( 'Foobar', fooSchema )
}
... Which resulted in the error:
/Users/me/project/node_modules/mongoose/lib/ES6Promise.js:21
throw 'Can\'t use ES6 promise with mpromise style constructor';
^
Can't use ES6 promise with mpromise style constructor
So I'm guessing thats not the right way to go... I thought it would be a better idea to return promises using the same promise library Mongoose has configured (Custom, or default..)
I tried to see how Mongoose does it by looking at the findOne function code, but I dont quite see how it returns a promise if theres no callback specified
P.S. Im using Mongoose 4.3.7
Update
Was just tinkering around, but would this be an acceptable method? Or is it bad practice
function tester(foo, cb){
return new Promise( ( res, rej ) => {
const result = 'You said ' + foo
if( typeof cb === 'function' ){
cb( null, result )
res() // Is this needed?
}
else {
res( result )
}
})
}
tester('foo', (err, data) => {
if( err )
console.log('ERROR!',err)
else
console.log('Result:',data)
})
tester('bar')
.then( data => {
console.log('Result:',data)
})
.catch( err => {
console.log('ERROR!',err)
})

just do this
mongoose.Promise = global.Promise
as simple as that

So I mainly didn't want to rely on a specific promise library, incase they were using a different one, but I realized that for the most part, it shouldnt really matter. So I decided to stick with Bluebird, and use the asCallback method
Heres the end result, this is with me coding a library with a function that supports both callbacks and promises; and in a separate file, and without requiring a specific promise library, using that function twice, once with a promise, and once with a callback:
// ./test-lib.js
'use strict'
const Promise = require( 'bluebird' )
module.exports = ( str, cb ) => {
const endResult = ( txt ) => new Promise( ( res, rej ) => res( 'You said ' + txt ) )
return endResult( str ).asCallback( cb );
}
// app.js
'use strict'
const Testlib = require('./test-lib')
Testlib('foo', ( err, data ) => {
if( err )
console.error('ERROR:',err)
else
console.log('DATA:',data)
})
Testlib('bar')
.then( data => {
console.log('DATA:',data)
})
.catch( err => {
console.error('ERROR:',err)
})
// Result:
// DATA: You said foo
// DATA: You said bar
That seems to have worked perfectly! (Thanks to tyscorp the Bluebird Gitter chat)

Related

NodeJS + mongoDB query after another : Promises/callback

I have three functions
A -> mongoDb query then call B then console.log("test")
B -> set some rules and call C
C --> mongoDb query go back to A -> console.log("test")
I am having a hard time with async/promises, after quite a long time I found a working solution that does not seem super elegant.
(Maybe because I'm not super familiar with async/await)
I was wondering if there's a better/more elegant/more readable solution?
Here's the code with only the "useful part". (The console.logs should write 1,2,3,4,5,6.)
app.get('/searchWingding', (req,res)=>{
users.findOneAndUpdate( mongoDBQuery
{returnOriginal : false})
.then(async () =>{
//remove unnecessary code for issue
console.log(1)
await wingdingsExhibitionRule(users,player, allWingdings)
console.log(6)
})})
async function wingdingsExhibitionRule(users,player, wingdingsList){
//remove unnecessary code for issue
console.log(2)
await changePlayerUnlock(users,player,"wingdingsExhibition")
console.log(5)
}
async function changePlayerUnlock(users,player,unlockRule){
//remove unnecessary code for issue
console.log(3)
const a = users.findOneAndUpdate(mongoDBQuery,
{returnOriginal : false})
.then(()=>{
console.log(4)
if(!checkStringInArray(player.unlock,unlockRule)){
player.unlock.push(unlockRule)
}
})
await a
}
```
You are using async-await syntax as well as promises. Your code can be written as shown below using only async-await syntax
app.get('/searchWingding', async (req,res)=> {
await users.findOneAndUpdate()
console.log(1)
await wingdingsExhibitionRule(users,player, allWingdings)
console.log(6)
async function wingdingsExhibitionRule(users,player, wingdingsList){
console.log(2)
await changePlayerUnlock(users,player,"wingdingsExhibition")
console.log(5)
}
async function changePlayerUnlock(users,player,unlockRule) {
console.log(3)
const a = await users.findOneAndUpdate()
console.log(4)
}

How to write a static method in Mongoose that gets all documents?

I'm new to Mongoose. I wrote a statics method and a instance method for a Mongoose schema named 'questionSchema' and exported it like so:
var questionSchema = new Schema({
...
})
questionSchema.methods.createQuestion = function(){
return this.save(function(err){
if(err){
return err
};
return 'Saved the question';
});
};
questionSchema.statics.getAllQ = function(){
return this.find({}, function(err, res){
if(err){
return err
};
return res;
});
}
module.exports = mongoose.model('Question', questionSchema)
Then in a route in my Node/Express server, I imported the it as a model, and tried calling the static method, which should return all the documents under the Question model:
const Question = require('../models/question.js');
...
router.post('/qcrud/submit', (req, res) => {
let reqBody = req.body;
var newQuestion = new Question({reqBody});
newQuestion.createQuestion();
})
router.get('/qcrud/getAll',(req, res) => {
let qArr = Question.getAllQ()
res.send(qArr);
});
However, it returns a Query object, not an array like I expected. I looked around and saw on MDN that
'If you don't specify a callback then the API will return a variable
of type Query.'
I did specify a callback, but still got the Query object. First of all, am I using my static and instance methods right? Are the documents even saving? And how do I access the array documents saved?
If you're using Node 8.x you can utilize async/await
This way your code will look more synchronous:
questionSchema.statics.getAllQ = async () => {
return await this.find({});
}
router.get('/qcrud/getAll',async (req, res) => {
let qArr = await Question.getAllQ();
res.send(qArr);
});
You can find a really nice article that is explaining how to use Mongoose with async/await here.

run mongoose methods synchronously in node.js

I'm trying to call getMarchandiseList() method that call a mongoose method " find({}) " in my marchandise router.
the problem is when I send the responce I find that I get a result=0 before the find({}) method send it's result
//the result should be
{id_marchandise : 01 , libelle_marchandise : 'fer'}.
[MarchandiseDAO.js][1]
*
var express = require("express");
var router = express.Router();
var marchandiseDAO = require ('../DAO/marchandises');
router.get('/listmarchandise', function (req,res) {
var marchandise = new marchandiseDAO();
marchandise.getMarchandiseList();
res.send("result" +marchandise.result);
});
module.exports = router;
*
[marchandiserouter.js][2]
var model = require("../Models/model");
var marchandiseDAO = function () {
console.log("get instance ");
this.result = 0 ;
}
marchandiseDAO.prototype.getMarchandiseList = function () {
console.log("begin");
model.MarchandiseModel.find({},function(err,marchandiselist){
console.log("traitement");
if(err) result = err;
else result = marchandiselist;
});
console.log("end");
}
You cannot run mongoose methods synchronously. But if you use a modern version of Node then you can make it appear as if it was run asynchronously.
Unfortunately you posted your code examples as screenshots which would require me to use Photoshop to fix your code, which is obviously not worth the hassle. So instead I will show you a general solution.
Using normal promises:
Model.find({...}).then(data => {
// you can only use data here
}).catch(err => {
// always handle errors
});
Using await:
try {
let data = await Model.find({...});
// you can only use data here
} catch (err) {
// always handle errors
}
The second example can only be used in an async function. See this for more info:
try/catch blocks with async/await
Use await outside async
Using acyns/await in Node 6 with Babel
When do async methods throw and how do you catch them?
using promises in node.js to create and compare two arrays
Keeping Promise Chains Readable
function will return null from javascript post/get

Use bluebird for mongoose, got ".bind is not a function"

I use bluebird for mongoose:
const Promise = require("bluebird");
const mongoose = require("mongoose");
mongoose.Promise = Promise;
And I want to use Promise.bind to share variable in the promise chain:
function getAutherOfBook(name)
{
return Book.findOne(
{
name: name
}, "-_id auther")
.then(doc =>
{
return doc.auther;
});
};
function geNationalityOfAuther(name)
{
return Auther.findOne(
{
name: name
}, "-_id nationality")
.then(doc =>
{
return doc.nationality;
});
};
getAutherOfBook("The Kite Runner")
.bind({})
.then(auther =>
{
this.auther = auther;
return geNationalityOfAuther(auther);
})
.then(nationality =>
{
console.log("auther: ", this.auther);
console.log("nationality: ", nationality);
})
.bind()
But I got the error: getAutherOfBook(...).bind is not a function
Maybe bluebird is not working for mongoose?
The problem you are having is that mongoose queries does not return full fledge promises -- directly quoting http://mongoosejs.com/docs/promises.html (v4.7.6)
// A query is not a fully-fledged promise, but it does have a `.then()`.
query.then(function (doc) {
// use doc
});
// `.exec()` gives you a fully-fledged promise
var promise = query.exec();
assert.ok(promise instanceof require('mpromise'));
In other words, the then function is syntax sugar and not a promise which is why the bind and other promise functions does not work.
To make it work, you either wrap it up in a full promise or use the exec function as suggested in the docs

How to use mongoose Promise - mongo

Can someone give me an example on how to use a Promise with mongoose. Here is what I have, but its not working as expected:
app.use(function (req, res, next) {
res.local('myStuff', myLib.process(req.path, something));
console.log(res.local('myStuff'));
next();
});
and then in myLib, I would have something like this:
exports.process = function ( r, callback ) {
var promise = new mongoose.Promise;
if(callback) promise.addBack(callback);
Content.find( {route : r }, function (err, docs) {
promise.resolve.bind(promise)(err, docs);
});
return promise;
};
At some point I am expecting my data to be present, but how can I access it, or get at it?
In the current version of Mongoose, the exec() method returns a Promise, so you can do the following:
exports.process = function(r) {
return Content.find({route: r}).exec();
}
Then, when you would like to get the data, you should make it async:
app.use(function(req, res, next) {
res.local('myStuff', myLib.process(req.path));
res.local('myStuff')
.then(function(doc) { // <- this is the Promise interface.
console.log(doc);
next();
}, function(err) {
// handle error here.
});
});
For more information about promises, there's a wonderful article that I recently read:
http://spion.github.io/posts/why-i-am-switching-to-promises.html
Mongoose already uses promises, when you call exec() on a query.
var promise = Content.find( {route : r }).exec();
Mongoose 4.0 Release Notes
Mongoose 4.0 brings some exciting new functionality: schema validation
in the browser, query middleware, validation on update, and promises
for async operations.
With mongoose#4.1 you can use any promises that you want
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
Another example with polyfilling global.Promise
require('es6-promise').polyfill();
var mongoose = require('mongoose');
So, you can just do later
Content
.find({route : r})
.then(function(docs) {}, function(err) {});
Or
Content
.find({route : r})
.then(function(docs) {})
.catch(function(err) {});
P.S. Mongoose 5.0
Mongoose 5.0 will use native promises by default if available,
otherwise no promises. You will still be able to set a custom promises
library using mongoose.Promise = require('bluebird');, however,
mpromise will not be supported.
I believe you're looking for
exports.process = function ( r, callback ) {
var promise = new mongoose.Promise;
if(callback) promise.addBack(callback);
Content.find( {route : r }, function (err, docs) {
if(err) {
promise.error(err);
return;
}
promise.complete(docs);
});
return promise;
};
On this page:http://mongoosejs.com/docs/promises.html
The title is Plugging in your own Promises Library
Use the bluebird Promise library like this:
var Promise = require('bluebird');
var mongoose = require('mongoose');
var mongoose = Promise.promisifyAll(mongoose);
User.findAsync({}).then(function(users){
console.log(users)
})
This is thenable, such as:
User.findAsync({}).then(function(users){
console.log(users)
}).then(function(){
// more async stuff
})

Resources