Mongoose repetitive callback

In mongoose there is one pattern i keep repeating:

Model.method(someParameterOrCondition, callback(error, result)=>{
  if (error) return console.log(error)
  done(null, result)
})

The callback is repeating everytime and each time i have to write it from start to bottom. I cant figure out how(if its possible) to declare it once and just reference to it in every method?

if the callback is the same for every function than yes, just assign a variable to the function definition

function callBack (err, result) {
if (error) return console.log(error)
done(null, result);
}

Model.method(someParameterOrCondition, callBack);
1 Like

hmm, i tried this and many other variations and none of them worked. Everytime the fcc tests fail and my page breaks

Sentences like none of them worked, tests fail and page breaks are not very useful to help you.

It also wastes the time of users, because they write solutions you already (?) tried out.

So please show us what you’ve already tried and exact error messages and descriptions.

1 Like

I am sorry, you are right, i think i have figured out why my attempts fail and there was no way someone would help me with the little info i gave initially.

Ill give a particular problem example, here is the task:

My solution code is:

const createAndSavePerson = (done) => {
  let John=new Person({name: 'John', age: 30, favoriteFoods: ['ketchup', 'carrot', 'potato']})
.save((err, data)=>{
    if (err){return console.log(err)}
    done(null, data)
  })
};

I havent included the prerequisite code, lets assume it correct as my solution passes the tests.
I want to move the callback which i employ in the .save() method outside of the createAndSavePerson body, to be able to use it in following solutions as majority of them use same construction. What i guess was failing my approach is i dont have access to the done parameter. The problem is i dont even know how the createAndSavePerson is called, where this parameter comes from and in what shape or form :wink: . I can only assume its the done function which is used in the end each time and somehow i need to reference to it in my own custom callback

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.