These are chat archives for Automattic/mongoose

13th
Jun 2016
Yogesh Patel
@ycpatel813
Jun 13 2016 06:30
Hi all
i have to find near by objectId of requested objectId is there any query for that??? Example
if my requested id is 5 then i need 3,4,5,6,7
if my requested id is 2 then i need 1,2,3,4,5
Jori Regter
@jdreg95
Jun 13 2016 14:17
Heya, if I want to add stuff to a returned document or collection? Would I have to use the lean option to change the result or is there a prettier way to do this?
Lets say, I'm doing a find() on a Model, I get a result [Model, Model...]. I want it to be { items: [Model, Model...], links: [], pagination: {} }
Mikołaj Stolarski
@grimor
Jun 13 2016 14:18
@jdreg95 you can use lean() if you don't need to access Mongoose methods. You can also do aggeration, but lean is more straightforward, but depending on case
Jori Regter
@jdreg95
Jun 13 2016 14:19
So lean() is fine for what i just described?
Mikołaj Stolarski
@grimor
Jun 13 2016 14:20

Oh, in that case you can just use

{
  items: results.toObject(),
  links: [],
  pagination: []
}

or use lean() and assign results to items without toObject()

Jori Regter
@jdreg95
Jun 13 2016 14:20
Currently I'm doing something like so:
Mikołaj Stolarski
@grimor
Jun 13 2016 14:20
In fact lean() will execute faster
Jori Regter
@jdreg95
Jun 13 2016 14:23
Calamity.find().lean().exec((err, results) => {
     const configuredCollection = configureCollection(
          configureItems(results, req),
          configureLinks(req),
          configurePagination(req)
      );

      res.json(configuredCollection).end();
});
Currenlty doing something like this
where every method just configures every key and so on
I'm also adding a links key to every document in results by the way
In the configureItems method
export function configureItems (items, {
  protocol,
  hostname,
  baseUrl,
  originalUrl
}) {
  return items.map(item => {
    item.links = [
      {
        rel: 'collection',
        href: `${protocol}://${hostname}${portString}${baseUrl}`
      },
      {
        rel: 'self',
        href: `${protocol}://${hostname}${portString}${originalUrl}`
      }
    ];

    return item;
  });
}
Like so.
So, using lean() here would be the option? There's not something like middleware to have those functions execute before returning the results? :P