Search code examples
mongoose

Alternative to retrieve data from "Query.prototype.exec()"?


I was trying to console.log() some data from my posts collection using Mongoose, but turns out it no longer accepts a callback function from the ".exec()" method, so what would be an alternative for this?

Here I was accessing my variable "posts" which holds my posts model (with "mongoose.model('Posts', schema)"):

posts.find({}).sort({'_id': -1}).exec((err, posts) => {
    console.log(posts[0]);
});

And here's the error: throw new MongooseError('Query.prototype.exec() no longer accepts a callback');


Solution

  • posts.find({}).sort({'_id': -1}).then((data)=>{console.log(data)}).catch((err)=>{console.log(err)})