node.js (节点:3341)弃用警告:猫鼬:妥协

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38138445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:21:36  来源:igfitidea点击:

(node:3341) DeprecationWarning: Mongoose: mpromise

node.jsmongodbmongoose

提问by Audel O. Gutierrez

I'm trying to develop a class on the top of the mongoose with my custom methods, so I extended the mongoose with my own class but when I invoke to create a new car method it works but its strip and error, here I let you see what I'm trying to do.

我试图用我的自定义方法在猫鼬顶部开发一个类,所以我用我自己的类扩展了猫鼬,但是当我调用创建一个新的汽车方法时,它可以工作,但它的剥离和错误,在这里我让你看看我在做什么。

I'm getting this warning

我收到此警告

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

after I do

在我做完之后

driver.createCar({
      carName: 'jeep',
      availableSeats: 4,
    }, callback);

driver is an instance of Driver class

driver 是 Driver 类的一个实例

const carSchema = new Schema({
  carName: String,
  availableSeats: Number,
  createdOn: { type: Date, default: Date.now },
});
const driverSchema = new Schema({
 email: String,
 name: String,
 city: String,
 phoneNumber: String,
 cars: [carSchema],
 userId: {
   type: Schema.Types.ObjectId,
   required: true,
 },
createdOn: { type: Date, default: Date.now },
});
const DriverModel = mongoose.model('Driver', driverSchema);

class Driver extends DriverModel {
  getCurrentDate() {
  return moment().format();
}
create(cb) {
  // save driver
  this.createdOn = this.getCurrentDate();
  this.save(cb);
}
remove(cb) {
  super.remove({
  _id: this._id,
 }, cb);
}
createCar(carData, cb) {
  this.cars.push(carData);
  this.save(cb);
}
getCars() {
  return this.cars;
 }
}

any thoughts about what Im doing wrong?

关于我做错了什么的任何想法?

回答by Hunter Lester

Here's what worked for me to clear up the issue, after reading docs: http://mongoosejs.com/docs/promises.html

这是我在阅读文档后解决问题的方法:http: //mongoosejs.com/docs/promises.html

The example in the doc is using the bluebird promise library but I chose to go with native ES6 promises.

文档中的示例使用 bluebird 承诺库,但我选择使用原生 ES6 承诺。

In the file where I'm calling mongoose.connect:

在我调用的文件中mongoose.connect

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://10.7.0.3:27107/data/db');

[EDIT: Thanks to @SylonZero for bringing up a performance flaw in my answer. Since this answer is so greatly viewed, I feel a sense of duty to make this edit and to encourage the use of bluebirdinstead of native promises. Please read the answer below this one for more educated and experienced details. ]

[编辑:感谢@SylonZero 在我的回答中提出了一个性能缺陷。由于此答案受到如此广泛的关注,我感到有责任进行此编辑并鼓励使用bluebird而非原生承诺。请阅读此答案下方的答案,了解更多受过教育和经验丰富的详细信息。]

回答by SylonZero

While the answer above is accurate and works, you have to account for the issue of Performanceif you have a real, production Node app.

虽然上面的答案是准确且有效的,但如果您有一个真正的生产 Node 应用程序,则必须考虑性能问题。

The solution above will use native ES6 promises - which are 4X slowerthan bluebird in the benchmarks I've shared below. This could dramatically affect the performance of an API written in Node and using MongoDB.

上面的解决方案将使用原生 ES6 承诺 -在我在下面共享的基准测试中比 bluebird慢 4 倍。这可能会极大地影响用 Node 编写并使用 MongoDB 的 API 的性能。

I recommend using Bluebird:

我建议使用蓝鸟:

// Assuming you store the library in a var called mongoose
var mongoose = require('mongoose');

// Just add bluebird to your package.json, and then the following line should work
mongoose.Promise = require('bluebird');

Benchmark Results

基准测试结果

Platform: (using latest Node at time of writing)

平台:(在撰写本文时使用最新的 Node)

  • Linux 4.4.0-59-generic x64
  • Node.JS 6.9.4
  • V8 5.1.281.89
  • Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz × 4
  • 16 GB RAM with 500 GB SSD
  • Linux 4.4.0-59-generic x64
  • 节点.JS 6.9.4
  • V8 5.1.281.89
  • Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz × 4
  • 16 GB RAM 和 500 GB SSD


    | file                                      | time(ms) | memory(MB) |
    |-------------------------------------------|----------|------------|
    | callbacks-baseline.js                     | 114      | 25.09      |
    | callbacks-suguru03-neo-async-waterfall.js | 152      | 32.98      |
    | promises-bluebird-generator.js            | 208      | 29.89      |
    | promises-bluebird.js                      | 223      | 45.47      |
    | promises-cujojs-when.js                   | 320      | 58.11      |
    | promises-then-promise.js                  | 327      | 64.51      |
    | promises-tildeio-rsvp.js                  | 387      | 85.17      |
    | promises-lvivski-davy.js                  | 396      | 81.18      |
    | callbacks-caolan-async-waterfall.js       | 527      | 97.45      |
    | promises-dfilatov-vow.js                  | 593      | 148.30     |
    | promises-calvinmetcalf-lie.js             | 666      | 122.78     |
    | generators-tj-co.js                       | 885      | 121.71     |
    | promises-obvious-kew.js                   | 920      | 216.08     |
    | promises-ecmascript6-native.js            | 931      | 184.90     |
    | promises-medikoo-deferred.js              | 1412     | 158.38     |
    | streamline-generators.js                  | 1695     | 175.84     |
    | observables-Reactive-Extensions-RxJS.js   | 1739     | 218.96     |
    | streamline-callbacks.js                   | 2668     | 248.61     |
    | promises-kriskowal-q.js                   | 9889     | 410.96     |
    | observables-baconjs-bacon.js.js           | 21636    | 799.09     |
    | observables-pozadi-kefir.js               | 51601    | 151.29     |
    | observables-caolan-highland.js            | 134113   | 387.07     |

回答by Krishan Kant Sharma

did you try this? For Example :

你试过这个吗?例如 :

const mongoose = require('mongoose')
mongoose.Promise = global.Promise // <--
const Schema = mongoose.Schema
const UserSchema = new Schema({
  name: String,
})
const User = mongoose.model('user', UserSchema)
module.exports = User

if you create a model from a mongoose instance who's promise wasn't redefined - every query on this model would throw the warning.

如果您从未重新定义承诺的猫鼬实例创建模型 - 此模型上的每个查询都会引发警告。

回答by Saurabh Lende

I think you have your answer but I use global.promisewith error handling

我想你有你的答案,但我使用global.promise和错误处理

// MongoDB connection
mongoose.Promise = global.Promise;

var promise = mongoose.connect('mongodb://localhost:27017/test_db', {
  useMongoClient: true,
});

promise.then(function(db) {
    console.log("Connected to database!!!");
}, function(err){
    console.log("Error in connecting database " + err);
});

回答by Yashwin Munsadwala

var mydb;
var uri = 'mongodb://localhost/user1';
var promise = mongooose.connect(uri,{
      useMongoClient: true,
});
promise.openUri(uri,function(errr,db){
if(errr){
        throw errr;
      }else{
        console.log("Connection Successfull");      
        mydb = db;
      }
});

One needs to have connection with the help of promise in the latest version of mongoose [this is the link][1] [1]: http://mongoosejs.com/docs/promises.html

需要借助最新版 mongoose [这是链接][1] [1] 中的 promise 建立连接:http: //mongoosejs.com/docs/promises.html

回答by dimpiax

Mongoose 4.8.6

猫鼬 4.8.6

If you catch error like this:

如果你捕捉到这样的错误:

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

(节点:9600)DeprecationWarning:Mongoose:mpromise(mongoose 的默认承诺库)已被弃用,请插入您自己的承诺库:http://mongoosejs.com/docs/promises.html

You need also to set in options which promise library to use for the driver.

您还需要设置用于驱动程序的承诺库的选项。

mongoose.Promise = global.Promise
mongoose.connect(uri, { useMongoClient: true, options: { promiseLibrary: mongoose.Promise }})

回答by sgtkuncoro

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
db = mongoose.connect(env.DATABASE_URI, function(){
  //
})

this work for me.

这对我有用。

回答by Aaman

Just add the second parameter as an object to the connect() method.

只需将第二个参数作为对象添加到 connect() 方法。

mongoose.connect('dbUrl', {
  useMongoClient: true
});

See: http://mongoosejs.com/docs/connections.html#use-mongo-client

请参阅:http: //mongoosejs.com/docs/connections.html#use-mongo-client