Mongoose, Model.create, Promises, unfamiliar pattern

Mongoose, Model.create, Promises, unfamiliar pattern
0.0 0


Sorry about the unintelligible title. I wasn’t sure how else to describe my issue.

I’m working on the Image Search Abstraction project and learning Angular at the same time. I used a [Yeoman] generator to setup a nice file/folder structure including a barebones API. It’s gone pretty well so far but there is a pattern in the generated API that I can’t decipher.

Basically it goes like this… I have a mongoose.model('collection', MyModel) and a function in the API used for adding new entries into MongoDB:

export function create(req, res) {
  return MyModel.create(req.body)
    .then(respondWithResult(res, 201))

The respondWithResult() function is what I’m having trouble understanding.

function respondWithResult(res, statusCode) {
  statusCode = statusCode || 200;
  return function(entity) {
    if(entity) {
      return res.status(statusCode).json(entity);
    return null;

I see in the mongoose documentation that .create() returns a promise, which I assume delays execution of the .then(). What entity refers to in the respondWithResult function is beyond me however. A similar patter is referenced in this stack overflow post.

Any tips on what is happening here would be very much appreciated.

Edit: I should add, inspecting the entity variable shows the object submitted to MongoDB (ie { __v: 0, term: ‘searchterm’, date: 2016-11-18T02:57:47.850Z, _id: 582e6e2b5219e6e2b5219 }). I’m not sure how, even as a callback function, it is initialized as a variable.


I’d imagine entity is passed to the function you recieve from respondWithResult()? So when the module is imported, you can do something like:

    //Import the function 
    var create = require('create');
    //respond is the function returned from create
    var respond = create(req, res);

    var entity = {
    "one": "hello",
    "two": "world"
    //returns JSON entity with status you send in create or 200 if status is null

I can’t really tell without the usage of the exported function though.