As documents returned by mongoose

0

I'm trying to manipulate a document that returns me a mongoDB query through mongoose but I manage to get it. I'm developing with Node.js with Koa and Mongoose framework as ODM.

The code is:

const Router = require('koa-router');
const RestaurantModel = require('models/restaurant.model');

class RestaurantRouter{

    static async get(ctx,next){
        ctx.body = await RestaurantModel.find();
    }

    static async getById(ctx){
        ctx.body='get';
    }
}

const router = new Router({prefix:'/restaurant'});

router.get('/', RestaurantRouter.get);
router.get('/:id', RestaurantRouter.getById);

module.exports = router;

I would need to be able to manipulate the document that RestaurantModel.find () returns to me; and embed it in another larger document and send it to the body of the response, something like

ctx.body = await {feature : RestaurantModel.find()};

I can not find the way since RestaurantModel.find () does not return the document itself but a Query object from which I can not get the document out.

Any suggestions?

Thank you!

    
asked by Fran 11.04.2017 в 17:44
source

1 answer

0

In Koa, the Content-Type is implicit according to the value you assign to ctx.body . In your case, you must assign an object to be returned by a JSON. I do not see any problem in your case, except for architectural details. You only need to wrap what the model returns in another object:

ctx.body = {
  feature: await RestaurantModel.find()
};

What will produce an answer like.

{
  "feature": [
    { ... },
    { ... },
    { ... }
  ]
}
    
answered by 11.04.2017 / 18:38
source