Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecation Warning #4291

Closed
saudelog opened this issue Jul 1, 2016 · 79 comments
Closed

Deprecation Warning #4291

saudelog opened this issue Jul 1, 2016 · 79 comments
Labels
help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary

Comments

@saudelog
Copy link

saudelog commented Jul 1, 2016

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

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?

@vkarpov15
Copy link
Collaborator

Hmm are you using promises anywhere? You shouldn't be getting this warning unless you use promises...

@vkarpov15 vkarpov15 added this to the 4.5.6 milestone Jul 1, 2016
@vkarpov15 vkarpov15 added bug? help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary labels Jul 1, 2016
@saudelog
Copy link
Author

saudelog commented Jul 1, 2016

nop I'm not using promises

@tsmith123
Copy link

I've just started to get this issue too. Not using promises that I know of!

@saudelog
Copy link
Author

saudelog commented Jul 4, 2016

I solved that warning doing

mongoose.Promise = global.Promise;

Right before calling mongoose.connect

// connect to mongo function
core.connect = function connect(opts) {
  mongoose.Promise = global.Promise;
  mongoose.connect(`mongodb://${opts.server}:${opts.port}/${opts.db}`);
  return mongoose.connection;
};

@vkarpov15
Copy link
Collaborator

Yeah this warning is supposed to tell you to change mongooses default promise lib if you're using promises, but it shouldn't happen unless you call .then somewhere

@IrishAdo
Copy link

IrishAdo commented Jul 8, 2016

I'm getting it but I'm only getting it where I save a object then modify it in the callback and save again

@sibelius
Copy link
Contributor

sibelius commented Jul 8, 2016

I've tried the @saudelog approach to assign a promise to mongoose before mongoose connect but I still receiving this error

I'm using async functions es7, and my code is blocked when I try to Model.findOne({})

@adam-s
Copy link

adam-s commented Jul 11, 2016

The solution @saudelog provides works. Like @IrishAdo I'm only getting this when saving an object also. Perhaps it is because of one of the mongoose plugins I'm using using Bluebird promise library.

Here is a list of dependencies I'm using

  "dependencies": {
    "async": "^2.0.0-rc.6",
    "body-parser": "^1.15.0",
    "bower": "^1.7.7",
    "compression": "^1.6.1",
    "connect-mongo": "^1.2.1",
    "consolidate": "^0.14.1",
    "cookie-parser": "^1.4.3",
    "express": "^4.13.4",
    "express-jwt": "^3.4.0",
    "express-session": "^1.13.0",
    "express-validator": "^2.20.8",
    "faker": "^3.1.0",
    "http-errors": "^1.5.0",
    "jsonwebtoken": "^7.0.1",
    "lodash": "^4.13.1",
    "method-override": "^2.3.5",
    "mongoose": "^4.4.3",
    "mongoose-beautiful-unique-validation": "^3.0.0",
    "mongoose-delete": "^0.3.3",
    "mongoose-validator": "^1.2.5",
    "morgan": "^1.6.1",
    "passport": "^0.3.2",
    "passport-local": "^1.0.0",
    "swig": "^1.4.2"
  }

@sitegui
Copy link

sitegui commented Jul 11, 2016

I'm not using plugins nor promises and getting this warning as well (on mongoose@4.5.3).

Running my app with "--trace-deprecation" I've got:

Trace: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead:
http://mongoosejs.com/docs/promises.html
    at Object.exports._printDeprecationMessage (internal/util.js:30:13)
    at Promise.deprecated [as then] (internal/util.js:54:22)
    at fnWrapper (.\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:188:11)
    at EmbeddedDocument.Object.defineProperty.value.fn (.\node_modules\mongoose\lib\schema.js:219:11)
    at _next (.\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:62:30)
    at fnWrapper (.\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:186:18)
    at EmbeddedDocument.Object.defineProperty.value.fn (.\node_modules\mongoose\lib\schema.js:173:18)
    at EmbeddedDocument._next (.\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:62:30)
    at EmbeddedDocument.proto.(anonymous function) [as $__original_save] (.\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:108:20)
    at .\node_modules\mongoose\lib\document.js:1917:24
    at new Promise.ES6 (.\node_modules\mongoose\lib\promise.js:45:3)
    at EmbeddedDocument.wrappedPointCut [as save] (.\node_modules\mongoose\lib\document.js:1893:14)
    at async.each.i (.\node_modules\mongoose\lib\schema.js:225:18)
    at .\node_modules\async\lib\async.js:181:20
    at Object.async.forEachOf.async.eachOf (.\node_modules\async\lib\async.js:233:13)
    at Object.async.forEach.async.each (.\node_modules\async\lib\async.js:209:22)
    at model.Object.defineProperty.value.fn (.\node_modules\mongoose\lib\schema.js:223:15)
    at _next (.\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:62:30)
    at fnWrapper (.\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:186:18)
    at .\node_modules\mongoose\lib\schema.js:200:17
    at .\node_modules\mongoose\node_modules\kareem\index.js:127:16
    at nextTickCallbackWith0Args (node.js:420:9)
    at process._tickDomainCallback (node.js:390:13)

@caal-15
Copy link

caal-15 commented Jul 12, 2016

I have the same issue, if it's any help it is specifically triggered when I try to create documents which have an array of subdocuments inside them, something like:

var data = {
  field: 'value',
  another_field: [{subdocfield1: 'value', subdocfield2: 'value'}]
} 

mySchema.create(data, cb)

It does not occur with other collections that do not have subdocs, it doesn't even happen if I issue the create statement without the subdoc data, like this:

var data = {
  field: 'value'
} 

mySchema.create(data, cb)

Note: mongoose.Promise = global.Promise did solve the warning problem for me though

@cameronus
Copy link

Experiencing same depreciation warning when I use remove() on a document. I am not using promises here or anywhere else in my code.

@benirose
Copy link

I just got this error when using Model.create(objects, callback);, perhaps this fix hasn't been published to npm yet?

@philgruneich
Copy link

Getting this, glad to read it is not alarming. I shall keep a closer look into this to help debugging when it happens.

@inolasco
Copy link

Getting this as well, and I'm not using mongoose promises anywhere.

I was able to trace it back to a model.save call inside a callback of the library on-headers, and the model was created outside the callback, before it was called, in case it helps anyone. Putting both the model creation and save call within the callback makes no difference.

@skatiyar
Copy link

skatiyar commented Aug 5, 2016

Facing this issue on node v4.4.6 whereas on v4.4.2 this seems to work

@vkarpov15
Copy link
Collaborator

@skatiyar code sample please

@ghost
Copy link

ghost commented Aug 8, 2016

same with me, getting this message after invoking save() method, enough for me to care

@ooade
Copy link

ooade commented Aug 9, 2016

This works! Before mongoose.connect(MONGO_URI); add mongoose.Promise = global.Promise;

@dvlsg
Copy link

dvlsg commented Aug 9, 2016

The following code is enough to reproduce on my end:

const mongoose = require('mongoose');
const schema = new mongoose.Schema({
  data: { type: Number }
});
const Model = mongoose.model('schema', schema);
mongoose.connect('mongodb://127.0.0.1:27017/somedatabase');
const newModel = new Model({ data: 1 });
const save = newModel.save(() => {
  console.log('saved model');
});
console.log(typeof save.then); //=> 'function'

Strange thing I can see here is that using newModel.save(callback) still returns a promise (or I'm assuming that's a promise, since the type of .then is 'function'). Is that expected behavior?

Here are my versions:
Node: v6.3.1
Mongoose: v4.5.8

Let me know if you need any other info from me.

@vkarpov15
Copy link
Collaborator

@dvlsg yes that's expected behavior currently, save will always return a promise even if you pass a callback

@dvlsg
Copy link

dvlsg commented Aug 14, 2016

Well, I guess that would at least explain why people are seeing the promise warning even when they don't think they're using promises.

@arkka
Copy link

arkka commented Aug 14, 2016

That explain everything.. I'm just a bit paranoid and wanted to get rid all of the warning 💃

@ghost
Copy link

ghost commented Aug 14, 2016

It's my fault, yup .save() returns a promise so this is expected, but still, warning made me wonder. http://mongoosejs.com/docs/promises.html (just had to read first paragraph 🎱)

@Spown
Copy link

Spown commented Feb 1, 2017

as a fellow Russian speaker I apologize for the behavior this lesser being has displayed an urge you not to translate what it has written here.

@protoEvangelion
Copy link

@vkarpov15 I have tried both mongoose.Promise = global.Promise; and mongoose.Promise = require('bluebird'); .

Unfortunately, I am still receiving the deprecation warning.

Is there something I am doing wrong?

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost/users_test');

mongoose.connection
  .once('open', () => {
    console.log('connectecd to db')
  })
  .on('error', (err) => {
    console.warn('Warning', err)
  });

@sobafuchs
Copy link
Contributor

@protoEvangelium Are you importing mongoose elsewhere in your app? Is this the first time mongoose is being used or is this file imported into another file?

Also what version of mongoose /node are you using?

@protoEvangelion
Copy link

@varunjayaraman This file is not being imported anywhere else. However, I am importing mongoose in my user.js schema file and then using that User schema in some of my tests.

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

node v7.0.0
mongoose v4.8.1

@sobafuchs
Copy link
Contributor

@protoEvangelium are you getting the warning in your app or only in your tests?

@Spown
Copy link

Spown commented Feb 3, 2017

I've had the same problem once - the culprit was another module, that used it's own mongoose dependency. Such modules have something like "mongoose": "^4.1.1" in their package.json, but since these modules are updated on an annual basis (if at all) - they lack the promise config part. @protoEvangelium are you using any other modules?

@MDShahrouq
Copy link

MDShahrouq commented Feb 6, 2017

@saudelog Thanks for the answer

@protoEvangelion
Copy link

@varunjayaraman I have only begun to test adding users to Mongo using Mongoose and Mocha. It is a barebones project so far.

@Spown I am using:

"mocha": "^3.2.0",
"mongoose": "^4.8.1",
"nodemon": "^1.11.0"

Thanks :)

@Spown
Copy link

Spown commented Feb 8, 2017

@protoEvangelium wait a minute, did you try this?

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.

@Worldedit05
Copy link

@Spown

I happened across this thread at the right time. I was receiving the same warning anytime I was saving information. Turns out I was creating a model from an instance of mongoose and was not redefining it. Requiring bluebird and setting it to mongoose.Promise resolved the error message.

Thanks so much!

@protoEvangelion
Copy link

@Spown Thank you sir! That was the issue. Interestingly, I defined mongoose.Promise = global.Promise; in my test_helper.js file right before connecting to Mongoose. I switched the mongoose.Promise = global.Promise; over to my file where I defined the Schema and it works!!!! No more deprecation warning 👍

const mongoose = require('mongoose')
mongoose.Promise = global.Promise;
const Schema = mongoose.Schema

@borislemke
Copy link

I'm getting this issue when using "populatable" virtuals in my schemas. Running my app with --trace-deprecations, you can see the culprit:

(node:8846) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
    at model.wrappedPointCut [as init] (/Users/fleavamini/Projects/stellium/stellium-express/node_modules/mongoose/lib/services/model/applyHooks.js:141:26)
    at completeMany (/Users/fleavamini/Projects/stellium/stellium-express/node_modules/mongoose/lib/query.js:1254:12)
    at Immediate.cb (/Users/fleavamini/Projects/stellium/stellium-express/node_modules/mongoose/lib/query.js:1117:13)
    at Immediate.<anonymous> (/Users/fleavamini/Projects/stellium/stellium-express/node_modules/mquery/lib/utils.js:137:16)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)

I have set the promise (note I'm using TypeScript):

import * as mongoose from "mongoose";
(<any>mongoose).Promise = global.Promise;
mongoose.connect('mongodb://localhost/blah')

Any ideas? Should I set the promise on every model that uses "populatable" virtuals? Hold on, I'm actually going to try that and come back with how it went.

@borislemke
Copy link

borislemke commented Feb 12, 2017

Okay, after some tinkering, I figured out that I still need to set the Promise on my Schema even if I have set it in the index of my server.

In my case, the website_pages collection was the first collection to ever get queried by my system, setting the mongoose.Promise to global.Promise on this schema alone has fixed the issue and I wasn't required to set it in all Schemas.

@pronebird
Copy link

pronebird commented Feb 12, 2017

Why not to use ES6 Promises? Aren't they available everywhere now?

mongoose.Promise = Promise; // eh?

ajscilingo added a commit to ajscilingo/two2er-nodejs that referenced this issue Feb 12, 2017
Mocha tests were throwing an EventEmitter error fixed by setting
require('events').EventEmitter.defaultMaxListerners = Infinity in app.js
detailed here: npm/npm#13806.

Mongoose Promises are apprently depricated, switch all uses of Mongoose
to use NodeJS's global promises instead detailed here:
Automattic/mongoose#4291

 Changes to be committed:
	modified:   app.js
	modified:   test/mongoConnectTest.js
	modified:   test/mongoStudentModelTest.js
	modified:   test/mongoTutorModelTest.js
	modified:   test/mongoUserModelTest.js
@afifkhaidir
Copy link

Thanks @Spown, I faced same deprecation warning since I put mongoose.Promise = global.Promise after importing model. Now the deprecation warning is gone.

@jsdevtom
Copy link

Declaring mongoose.Promise = global.Promise in the model file as mentioned by @Spown works. This is due to node's caching of required modules. This seems fickle though. Is there not a way of ensuring that the test_helpers.js is loaded first so that I can set mongoose's promise function in this file?

@Spown
Copy link

Spown commented Feb 16, 2017

Is there not a way of ensuring that...

personally I require mongoose only once in my projects, then I put it into a global Singleton object and use it everywhere for all DB purposes. Not exactly graceful, but mostly bulletproof. and I've been doing it long before the deprecation thing simply because if you use a custom connection, which I do (a connection made via mongoose.createConnection() instead of mongoose.connect()) - you have to create models from the mongoose instance linked to this connection. Otherwise it just won't work at all which is much worse than some pesky warning.

@sobafuchs
Copy link
Contributor

yeah I do the same as @Spown. It's certainly not ideal, but it's the only way to keep mongoose backwards compatible until the next major release when we can deprecate mpromise completely

sftl pushed a commit to sftl/mcFly---Api that referenced this issue Feb 19, 2017
	1 - added "test" as a new key of "script".  to run the tests type "npm test".
	2 - added "chai", "chai-http", "mocha" modules in "devDependencies".

* In dist.js (gulp task):
	1 - Replaced clean() by clean({force: true});

* In tweets.routes.js:
	1 - Replaced require(__dirname + '/tweets.controllers') by require('./tweets.controllers');

* In tweers.model.js:
	1 - Fixed some schema paths. Replaced "require" by "required".
	2 - exports the model.

* In tweets.controllers.js:
	1 - In function addNew: removed the manual check of the required params. Now required params are validated by the schema, remember that we fixed the "require" path with "required".

* In mongoose.js:
	1 - Descommented 'mongoose.Promise = global.Promise;'. Ref: Automattic/mongoose#4291
@htchaan
Copy link

htchaan commented Feb 26, 2017

libs/mongoose.js

import mongoose from 'mongoose'; // real mongoose only be required once here 

mongoose.Promise = global.Promise; // so that you dont have to do this on every require
const Schema = mongoose.Schema;

export {
  mongoose as default, // kind of singleton
  mongoose,
  Schema,
};

index.js

import mongoose from './libs/mongoose';
mongoose.connect(process.env.MONGODB_URI);

models/user.js

import {mongoose, Schema} from '../libs/mongoose';

export default mongoose.model('User', new Schema({
  name: String,
  password: String,
}));

@pronebird
Copy link

pronebird commented Feb 26, 2017

@howard require() calls are cached.

@shmuelgutman
Copy link

So, if I understand correctly, I need to set the promise before every schema declaration instead of doing it only in one place (for example in my index file or where I'm setting the connection)
This is not a good practice, worth consider to change it to a function, something like:
mongoose.setPromise(global.Promise);

@baxterw3b
Copy link

@sh-guti i think so, i had the same problem and that piece of code solve that.

At this point i don't know, if to use callbacks or promises. LOL.

@nandofalcao
Copy link

Use

mongoose.createConnection(URI)

@pronebird
Copy link

Can anyone explain, why on Earth mongoose denies the existence of native Promises and can't use them out of box?

@vkarpov15
Copy link
Collaborator

Backwards compatibility. Mongoose 4.x was around for over a year before node 4 was released. We'll switch over with the next backwards breaking release.

@MickL
Copy link

MickL commented Dec 9, 2017

When will this be?

@jondo89
Copy link

jondo89 commented Dec 11, 2017

mongoose.createConnection(URI) causes a very strange bug with Mongoose , hours of debugging with queries not working . eventually went back to

mongoose.connect(process.env.MONGODB); from mongoose.createConnection(process.env.MONGODB)

as a side note , it did stop the depreciation warning .. but stopped everything working ...

@vkarpov15
Copy link
Collaborator

@MickL we will have an rc0 out in tbe next few weeks, follow mongoose on twitter or join the slack channel for updates

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary
Projects
None yet
Development

No branches or pull requests