mongo-cursor-pagination icon indicating copy to clipboard operation
mongo-cursor-pagination copied to clipboard

How to use Fields parameter with Mongoose paginate

Open ptrk8 opened this issue 7 years ago • 6 comments

Current Behaviour

The following fields parameter in my Mongoose query is not recognised by paginate function since the query simply returns the entire result including "bids.bid", which I am explicitly excluding. It appears any fields I include are disregarded.

Additionally, whenever I include a "fields" parameter in the paginate function, the _id is also never returned; however, removing the "fields" parameter entirely brings back the _id field as expected.

List.paginate({
	query: query,
	limit: paginationLimit,
	fields: {
		"bids.bid": 0
	}
}).then((result) => {
	sendJsonResponse(res, 200, result);
}).catch((err) => {
	sendJsonResponse(res, 404, err);
});

Expected Behaviour

The documentation for the paginate function refers to the find section so I was expecting the "fields" parameter to work as it does when not using Mongoose.

How should I exclude/include certain fields from my query using Mongoose and paginate?

ptrk8 avatar Jul 09 '18 13:07 ptrk8

I am having the exact same issue with version 7.0.0

kontextbewusst avatar Jul 25 '18 12:07 kontextbewusst

We have the same problem, quick fix is to do

List.paginate({
	query: query,
	limit: paginationLimit,
	fields: {
              fields: {
		"bids.bid": 0
                }
	})

This way it is excluded, but is ugly as hell

uncledent avatar Sep 08 '18 18:09 uncledent

Also a bad idea above, the _id field will disappear

uncledent avatar Sep 08 '18 18:09 uncledent

it seems this is caused by a bug;

mongoist API's findAsCursor method uses projection as second param see docs

where as official mongodb driver uses options object as second param see docs

mongo-cursor-pagination currently does not account for this difference see src code thus doesn't properly pass the projection in the case mongodb native client is used

chrisdostert avatar Nov 13 '18 02:11 chrisdostert

I'm having the same issue. I'm using the workaround above but re-including the id:

List.paginate({
  fields: {
    _id: 1,
    fields: {
      other: 1,
      items: 1 
    }
  }
})

antony avatar Dec 08 '18 19:12 antony

I'm having the same issue. I'm using the workaround above but re-including the id:

List.paginate({
  fields: {
    _id: 1,
    fields: {
      other: 1,
      items: 1 
    }
  }
})

A slight modification of this worked for me.

List.paginate({
  fields: {
    _id: 1,
   projection: { other: 1, items: 1 }
  }
});

Mentioning only projection property will strip of the _id property. If you do want the _id property, above workaround worked good for me.

The fix for the above issue is raised in the PR #357. But because of this issue (#361), I think PR is not getting approved and merged. Hope this is fixed sooner

AraosDev avatar Oct 26 '23 05:10 AraosDev