Reputation: 43
I am trying to get all users from the database but it shows Model.find() no longer accepts a callback. I am not able to figure out how I can get the data from mongodb database.
router.get('/users',(req,res) => {
User.find({},(err,data) => {
if(err) throw err;
res.send(data)
})
})```
Upvotes: 0
Views: 4697
Reputation: 1
Add New keyword in your models.js file. This worked for me
const mongoose = require("mongoose");
const urlSchema = new mongoose.Schema(
{
shortId: {
required: true,
unique: true,
type: String,
},
redirectURL: {
type: String,
required: true,
},
visitHistory: [
{
timestamp: {
type: Number,
},
},
],
},
{
timestamps: true,
}
);
const URL = mongoose.model("url", urlSchema);
module.exports = URL;
Upvotes: 0
Reputation: 102247
migrating_to_7.html#dropped-callback-support:
Model.find
method no longer accepts callback. It always returns a promise. You can use the async/await
or .then()/.catch()
method to handle the promise like:
try {
cont res = await User.find({})
} catch(e) {
console.error(e)
}
You can find the method list in the above link. Let's also take a look at the source code of Model.find()
method:
Model.find = function find(conditions, projection, options) {
_checkContext(this, 'find');
if (typeof arguments[0] === 'function' || typeof arguments[1] === 'function' || typeof arguments[2] === 'function' || typeof arguments[3] === 'function') {
throw new MongooseError('Model.find() no longer accepts a callback');
}
const mq = new this.Query({}, {}, this, this.$__collection);
mq.select(projection);
mq.setOptions(options);
return mq.find(conditions);
};
The method will verify the arguments and throw that error if a callback argument is passed in.
Upvotes: 0
Reputation: 87
Here is what you can use instead of a callback:
router.get('/users',(req,res) => {
User.find({}).then(
data => res.send(data)
).catch(
err => throw err
);
});
or with Async/await:
router.get('/users', async (req,res) => {
try {
const data = await User.find({});
res.send(data);
} catch (err) {
throw err;
}
});
Good luck!
Upvotes: 1
Reputation: 43
Here we use async await to solve this issue
Also don't promisify it
const data = await Model.find()
router.get('/allUsers', async (req, res) => {
const allUsers = await User.find()
res.status(200).send({
status: 'Success',
data: allUsers,
})
Upvotes: 2