Mongoose's default promise library is deprecat

2019-01-26 09:42发布

问题:

I'm trying to start a MEAN-stack server, however I'm getting this error msg:

Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

I tried to search some answers here but the one that I found wasn't clear enough for me:

(node:3341) DeprecationWarning: Mongoose: mpromise

I found the file calling the mongoose.connect, but the codes on that issue didn't work for me, can anyone explain for me how it works?

回答1:

use this code,before the mongo connection and this will resolve the promise problem.

mongoose.Promise = global.Promise;


回答2:

The way I usually connect to MongoDB is by using the Bluebird promise library. You can read more about it in this post. With any luck, this snippet below will help you get started, as it is what I use when prototyping.

let mongoose = require('mongoose');
let promise = require('bluebird');
let uri = 'mongodb://localhost:27017/your_db';
mongoose.Promise = promise;
let connection = mongoose.createConnection(uri);


回答3:

Latest mongoose library, do not use any default promise library. And from Mongoose v 4.1.0 you can plug in your own library.

If you are using mongoose library(not underlying MongoDB driver) then you can plug in promise library like this:

//using Native Promise (Available in ES6)
mongoose.Promise = global.Promise;

//Or any other promise library
mongoose.Promise = require('bluebird');

//Now create query Promise
var query = someModel.find(queryObject);
var promise = query.exec();

If you are using MongoDB Driver then you will need to do some extra effort. Because, mongoose.Promise sets the Promise that mongoose uses not the driver. You can use the below code in this case.

// Use bluebird
var options = { promiseLibrary: require('bluebird') };
var db = mongoose.createConnection(uri, options);



回答4:

Work for me.

Mongoose v4.11.7 resolve the promise problem

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connection.openUri('mongodb://127.0.0.1:27017/app_db', { /* options */ });

Mongoose #save()

var article = new Article(Obj);
article.save().then(function(result) {
    return res.status(201).json({
        message: 'Saved message',
        obj: result
    });
}, function (err) {
    if (err) {
        return res.status(500).json({
            title: 'Ac error occurred',
            error: err
        });
    }
});