簡體   English   中英

Mongoose | 復用查詢 object

[英]Mongoose | Reuse query object

我正在嘗試使用文檔總數( count )計算skiplimit
問題是查詢 object 在我嘗試獲取items時返回count數值。

跟隨一個例子:

const query = MyModel.find().or([AbilityRule1, AbilityRule2, ...]);
const count = await query.countDocuments(); // count = 3
// Some logic to compute the values of `skip` and `limit` with `count`
// const skip = ...
// const limit = ...
const items = await query.skip(skip).limit(limit); // items = 3 instead of [Model, Model, Model]

countDocuments()看起來是Model的方法,而不是Query 我猜你在這里使用它的方式是在現有查詢 object 上調用它,你可能只是在覆蓋它。

為什么不只是:

const query = MyModel.find();
const count = await MyModel.countDocuments();
// ...
const items = await query.skip(skip).limit(limit);

當我嘗試實現分頁時,我發現自己有一個類似的問題。 我想出的答案是在Query object 上使用merge function。

const query = MyModel.find().or([AbilityRule1, AbilityRule2, ...]);

const count = await MyModel.find().merge(query).countDocuments();

const items = await query.skip(skip).limit(limit);

來源: https://mongoosejs.com/docs/api/query.html#query_Query-merge

受馬修回答的啟發:

我添加這個答案是因為我發現第二條和第三條指令不依賴於MyModel很重要,它們只依賴於query object。

const query = MyModel.find().or([AbilityRule1, AbilityRule2, ...]);

const count = await query.model.find().merge(query).countDocuments();
const items = await query.skip(skip).limit(limit);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM