Mongoose: How to use this model instance outside the callback?

Instead of creating an instance of a model, and saving it on a different step like this:

// Create an instance of model SomeModel
var awesome_instance = new SomeModel({ name: 'awesome' });


// Save the new model instance, passing a callback
awesome_instance.save(function (err) {
  if (err) return handleError(err);
  // saved!
});

I want to to do it all in a single step like this:

SomeModel.create({ name: 'also_awesome' }, function (err, awesome_instance) {
  if (err) return handleError(err);
  // saved!
});

The thing is that if I use the second case, I don’t know what would be a proper way to access the awesome_instance outside the callback, the keep working with it. I could assign it to global variable, but I just think there must be a “better” way.

Hmm… I haven’t used it this way, but what if you have a function where you want to use the instance and call that function itself as a callback.

const myCallback = (err, awesome_instance) => {
  // Use it how you want here
}
SomeModel.create({ name: 'also_awesome' }, myCallback);
1 Like

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