This is the sixth day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Mongoose built in support of Promises. In asynchronous operations above Mongoose 5.x, such as.save() and.find().exec() return a Promise unless you pass a callback function.

const Model = mongoose.model('test', Schema({
  name: String
}))
​
const doc = new Model({ name: 'O.O' })
​
const promise = doc.save()
console.log(promise instanceof Promise) // true/ / callback
const res = doc.save(function callback(err) {
  / *... * /
})
​
console.log(res) // undefined
Copy the code

mongoose.Promiseattribute

The Mongoose singleton has a Promise property that can be used to set the Promise library used by Mongoose. For example, you could have Mongoose use the popular Bluebird Promise library:

const Bluebird = require('bluebird')
​
// Let Mongoose use Bluebird instead of built-in Promises.
mongoose.Promise = Bluebird
​
const doc = new Model({ name: 'D.O' })
​
const promise = doc.save()
promise instanceof Promise // false
promise instanceof Bluebird // true
Copy the code

If you have not upgraded to Mongoose 5.x or higher, you may see the following deprecation warnings in Mongoose 4.x:

WARNING: Mongoose: mpromise (mongoose’s default promise library) is deprecated, plug in your own promise library instead

To resolve the deprecation warning, add the following code:

mongoose.Promise = global.Promise
Copy the code

That’s because one of the big changes in Mongoose 5.x is the switch to node.js’s native Promise. Mongoose 4.x was released prior to ES6, so it has its own promise implementation that is slightly different from native JavaScript Promises.

If you see Mongoose. Promise = global.Promise in code that uses Mongoose 5, remove it. By default, Mongoose 5.x uses native Promises, so this code will not work in Mongoose 5.

QueryNot a Promise

The save() method returns a Promise, and Mongoose’s find() method returns a Mongoose Query.

const query = Model.find()
​
query instanceof Promise // false
query instanceof mongoose.Query // true
Copy the code

Mongoose queries are optional. In other words, the query has a THEN () method that behaves like the Promise THEN () method. Therefore, you can use queries with Promise chains and async/await.

// Use a query with a promise chain
Model.findOne({ name: 'D.O' })
  .then(doc= > Model.updateOne({ _id: doc._id }, { name: 'O.O' }))
  .then(() = > Model.findOne({ name: 'O.O' }))
  .then(doc= > console.log(doc.name)) // O.O// query with async/await
const doc = await Model.findOne({ name: 'O.O' })
console.log(doc.name) // O.O
Copy the code