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
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?
It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.
You don't handle a Promise with a callback: mongoose call you're callback if provided, otherwise it return the Promise.
Mongoose is similar to an ORM (Object-Relational Mapper) you would use with a relational database. Both ODMs and ORMs can make your life easier with built-in structure and methods. The structure of an ODM or ORM will contain business logic that helps you organize data.
If you're an advanced user, you may want to plug in your own promise library like bluebird. Just set mongoose. Promise to your favorite ES6-style promise constructor and mongoose will use it.
Here's what worked for me to clear up the issue, after reading docs: 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.
In the file where I'm calling 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 bluebird
instead of native promises. Please read the answer below this one for more educated and experienced details. ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With