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

十年热恋 提交于 2020-01-05 08:03:43

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/41517477/use-bluebird-for-mongoose-got-bind-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!