I am learning JS. I was working with Mongoose and I wanted do pass a function and parameter(s) to a callback, but I have to use call() instead.
// Car is a model. Using Express in Node.js
express.Router().route('/')
.get((req,res,next)=>{
print(res,next,Cars.find)
})
const print = async(res,next,func,param1={})=>{
try {
const cars = await func.call(Cars,param1)
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(cars);
} catch (err)
next(err);
}
It does not work for me when I simply do func(param1) inside print(...), which returns this error.
MongooseError: `Model.find()` cannot run without a model as `this`.
Make sure you are calling `MyModel.find()` where `MyModel` is a Mongoose model.
Could you please explain why that is and when I need to use apply()/call() to pass in this? In this context of Mongoose and in general?
Also I'm a bit confused on next() and next(err). Documentation says it's just so the program can "skip" the error in some sense and I can visibly see that. But is it like a callback function that we can modify or it's something built in?
EDIT: Im looking at How to access the correct `this` inside a callback and is it because somehow the object is not passed into print()
?