How to use mongoose Promise - mongo - node.js

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
})

Related

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.

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

Unit testing / Mocking mongoose models with sinon

so I have a node module like:
let mongoose = require('mongoose'),
User = mongoose.model('User');
module.exports = (req, res, next) => {
User.findById(req.user)
.then(user => {
req.body.user = user._id;
req.body.company = user.company;
next();
}, err => {
req.send(400, err);
});
};
So, in this case, I want to ensure the proper things are attached to the req.body. So, how would I go about mocking the User function? I have to load the model first so this code doesn't throw an error before calling mongoose.model so maybe something to do with actually stubbing the global require? Thanks for any advice!
So, I just discovered proxyquire https://www.npmjs.com/package/proxyquire and it was like the heavens opened and shined a light down upon me for the most glorious "ah ha" moment. No more having to load models in mongoose before trying to use them!
The code to mock mongoose looks something like:
const proxyquire = require('proxyquire'),
expect = require('chai').expect,
Promise = require('bluebird'),
_ = require('lodash'),
USERID = 'abc123',
COMPANY = 'Bitwise',
mongooseStub = {
mongoose: {
model: (name, schema) => ({
findById: () => {
return new Promise((resolve, reject) => {
resolve({_id: USERID, company: COMPANY});
});
}
})
}
},
attachUser = proxyquire('../lib/users/attach-user', mongooseStub);
That will effectively load the attach-user module, while stubbing out the mongoose.model function to return something I can control. Then the rest of my test just calls out to the module function and can make assertions as expected.

Creating a Mongoose plugin that supports callbacks AND promises

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)

Why koa-router sends 404?

I'm using a koa-router, koa-views and sequelize. Data comes from a database, but the status = 404. What am I doing wrong?
router.get('/', function *() {
var ctx = this;
yield models.drivers.findAll({
where: {
userId: ctx.passport.user.id
}
}).then(function(drivers) {
ctx.render('driversSearch', {
drivers: drivers
});
});
});
Looks like you're not taking advantage of Koa's coroutine features. Your code can be rewritten like this:
router.get('/', function *() {
var drivers = yield models.drivers.findAll({
where: {
userId: this.passport.user.id
}
});
this.render('driversSearch', {
drivers: drivers
});
});
Koa uses the co library under the hood. If you yield a promise, the generator function will pause and then resume when the promise is fulfilled.

Resources