我尝试使用bluebird进行Promisify Mongoose连接,我需要减少回调,所以我使用了bluebird.But它给了我下面的错误。
var expect = require('chai').expect;
var mongoose = require('mongoose');
var jobModel = require('../models/job');
var Promise = require('bluebird');
function resetJobs() {
return new Promise(function(resolve, reject) {
mongoose.connection.collections['jobs'].drop(resolve, reject);
});
};
function findJobs(query) {
return Promise.cast(mongoose.model('Job').find({}).exec());
};
var connectDB = Promise.promisify(mongoose.connect,mongoose);
describe('get jobs', function() {
it('Should not be empty since jobs are seeded', function(done) {
connectDB('mongodb://localhost/jobfinder').then(function() {
resetJobs()
.then(jobModel.seedJobs)
.then(findJobs).then(function(jobList) {
expect(jobList.length).to.be.at.least(1);
done();
});
});
});
});
但这给了我一个错误
Unhandled rejection TypeError: Cannot read property 'connection' of undefined
at Mongoose.connect (F:\MyProjects\JobFinder\node_modules\mongoose\lib\index.js:232:18)
at tryCatcher (F:\MyProjects\JobFinder\node_modules\bluebird\js\release\util.js:11:23)
at ret (eval at <anonymous> (F:\MyProjects\JobFinder\node_modules\bluebird\js\release\promisify.js:184:12), <anonymous>:14:23)
at Context.<anonymous> (F:\MyProjects\JobFinder\test\jobs-data-spec.js:22:3)
我正在使用的软件包版本如下
"bluebird": "^3.1.1",
"express": "^4.13.4",
"mongoose": "^4.3.6"
答案 0 :(得分:3)
我正在制作相同的教程 Bluebird改变了3.0中的api // 2.x Promise.promisify(fn,ctx); // 3.0 Promise.promisify(fn,{context:ctx});
我更改了呼叫,并且呼叫停止抛出错误。
点击此处查看Bluebird说明: http://bluebirdjs.com/docs/new-in-bluebird-3.html
希望这有帮助
答案 1 :(得分:2)
以下代码似乎对我有用。
var connectMongoose = Promise.promisify(mongoose.connect, {context: mongoose});
connectMongoose('MONGO_URL', mongoose)
.then(..)
答案 2 :(得分:1)
我也在制作同一个教程,这就是我为解决这个问题所做的工作。
npm uninstall bluebird
npm install --save bluebird@2.0
然后当您使用mocha
运行测试时,您应该通过。
答案 3 :(得分:0)
你也可以手动promisify mongoose.connect,而不使用bluebird:
const mongoose = require('mongoose');
const { promisify } = require('util');
const connectMongoose = promisify((resolve, reject) => {
const options = { useNewUrlParser: true, useUnifiedTopology: true };
const uri = 'mongodb+srv://<USERNAME>:<PASSWORD>' +
'@cluster0.iz4o8.mongodb.net/<DB-NAME>?retryWrites=true&w=majority';
try {
mongoose.connect(uri, options, resolve);
} catch (err) {
reject(err);
}
});
(async () => {
try {
await connectMongoose();
console.log('connected to monoose! :)');
}
catch (err) {
console.error('could not connect to mongoose :(', err);
process.exit(-1);
}
})();