Paginate in revert order with mongoose-paginate-v2 - node.js

Is it possible to paginate mongodb in revert order, using mongoose-paginate-v2 given that I have field: createdAt.
For example, my collection have docs: 1-2-3-4-5-6-7-8-9-10
1 is the first doc to be created, 10 is the lastest/newest doc.
When I use mongoose-paginate-v2 to paginate that collection, the pagination work this way:
with page size = 3, it returns: page1: 1-2-3, page2: 4-5-6, page3: 7-8-9, page4: 10.
How can I use mongoose-paginate-v2 to have result like:
page1: 10-9-8, page2: 7-6-5, page3: 4-3-2, page4: 1
This is the package: https://www.npmjs.com/package/mongoose-paginate-v2

You can pass sort option as an argument to paginate method as per the documentation.
E.g.
const options = { sort: { createdAt: -1 }}
Model.paginate(yourQuery, options)

Related

ravendb NodeJS, load related document and create a nested result in a query

I have an index that returns something like this
Company_All {
name : string;
id : string;
agentDocumentId : string
}
is it possible to load the related agent document and then generate a nested result with selectFields and QueryData like this
ICompanyView {
companyName : 'Warner',
user {
documentId : 'A/1'
firstName : 'john',
lastName : 'paul'
}
}
I need something like the below query that obviously doesn't work as I expect:
const queryData = new QueryData(
["name", "agentDocumentId", "agent.firstName", "agent.lastName"],
["companyName", "user.documentId", "user.lastName", "user.firstName"]);
return await session.query<Company_AllResult>({ index: Company_All })
.whereEquals("companyId", request.companyId)
.include(`agents/${agentDocumentId}`) // ????
.selectFields(queryData,ICompanyView)
.single();
Yes, you can do that using:
https://ravendb.net/docs/article-page/5.4/nodejs/indexes/indexing-related-documents
This is called indexing related documents, and is accessible at indexing time, not query time.
Alternatively, you have the filter clause, which has access to the loaded document, but I wouldn't generally recommend doing this.
Generally:
When you query an index, the results of querying the index are the documents from the collection the index was defined on.
Index-fields defined in the index are used to filter the index-query
but the results are still documents from the original collection.
If you define an index that indexes content from a related-document then when making an index-query you can filter the documents by the indexed-fields from the related documents, but the results are still documents from the original collection.
When making an index-query (or any other query) you can project the query results so that Not the full documents of the original collection are returned but some other object.
Now:
To project/get data from the indexed related-document you have 2 options:
Store the index-fields from the related-document in the index.
(Store all -or- specific fields).
This way you have access to that content when making a projection in your query.
See this code sample.
Don't store the index-fields from the related-document,
then you will be able to use the index-fields to filter by in your query,
but to get content you will need to use 'include' feature in your query,
and then use the session.load, which will Not make another trip to the server.
i.e. https://demo.ravendb.net/demos/nodejs/related-documents/query-related-documents

Mongoose: Is it possible to use populate on a field of type array to return only X number of elements of that array?

I have this model:
const UserSchema = new Schema({
following: [
{
type: Schema.Types.ObjectId,
ref: "users",
},
],
});
module.exports = User = mongoose.model("users", UserSchema);
I would like to use populate on the following field, BUT return only the first 5 elements of that array.
Is this possible to do this directly with populate?
I know I can do this array truncation lately after getting all the array elements. But, what I am doing is in a complex query, and I wouldn't like to complicate it any further.
Thank you.
https://mongoosejs.com/docs/populate.html#limit-vs-perDocumentLimit
Populate does support a limit option, however, it currently does not limit on a per-document basis for backwards compatibility. For example, suppose you have 5 following:
Limit
if you want to get a total of 5 following regardless of the number of users
const users = await User.find().populate({
path: 'following',
options: { limit: 5 }
});
That's because, in order to avoid executing a separate query for each document, Mongoose instead queries for fans using numDocuments * limit as the limit. If you need the correct limit, you should use the perDocumentLimit option (new in Mongoose 5.9.0). Just keep in mind that populate() will execute a separate query for each story, which may cause populate() to be slower.
perDocumentLimit
if you want to get a total of 5 following per user
A special option that tells Mongoose to execute a separate query
for each User to make sure we get 5 following for each user.
const users = await User.find().populate({
path: 'following',
options: { perDocumentLimit: 5 }
});

Does loopback 3 supports where filter with skip + limit?

I am working on Loopback with version 3,
Does It supports where filter with skip and Limit, I am trying to apply for pagination.
For pagination, I have always used "offset" but in docs there is an option for skip also. Please checkout at skip in loopback3
If you want apply skip and limit with pagination. This code is help full for you.
example is now :
Users.getList = function (filter, cb) {
Users.find({
where: {
condition
},
limit: filter.limit,
skip: filter.skip
})
}
You can use skip and limit in the loopback where condition. I assume that you are trying to get the answer for something like the query SELECT * FROM schemaName.tableName limit 10,5 using loopback, for that you can use the following peace of code
modelName.find({
order: 'id DESC',
skip: 10,
limit: 5,
});

Select Substring of Column in Sequelize

I am working with sequelize. I want to select a substring in my where clause like this in SQL SUBSTRING(description_column, 1, 200). I am selecting by page, pagesize and limiting description_column to length of 200. I don't know if I can achieve it with raw query since I want pagination which findAll and FindAndCountAll offers which I want to use. How can I achieve this? The only substring I find in sequelize works this way
[Op.substring]: 'hat' // LIKE '%hat%'
You can use Sequelize.literal() to use the Standard SQL functions:
const options = {
attributes: [
'id',
sequelize.literal('SUBSTRING(description_column, 1, 200) as description_column')
]
}
MyTable.find(options).success(success);

Is there any way to optimize this MongoDB query for pagination in Node.js

I am paginating through a very large collection of documents. I was wondering if this an efficient means of pagination in mongoDB using _id's. My concern is that every time I make the query the entire collection of id's would need to get sorted before a result could be returned. I saw this document on optimizing queries with indexes, but would this apply to me since Im querying on _id which I would've thought is already indexed?
Pagination function:
function paginateDocs(currId, docsPerPage) {
const query = currId ? { _id: { $gt: currId } } : {};
const queryOptions = { limit: usersPerPage, sort: '_id' };
return mongo.find(query, queryOptions).toArray();
}
You can use cursor.hint(index) where you can define index as what all indexes on which you want to sort on. Refer to this link->
https://docs.mongodb.com/manual/reference/method/cursor.hint/

Resources