猫鼬 |重用查询对象

时间:2021-04-09 18:29:25

标签: node.js mongoose

我正在尝试使用文档总数 (skip) 计算 limitcount
问题是当我尝试获取 count 时,查询对象返回 items 值。

举个例子:

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]

3 个答案:

答案 0 :(得分:1)

Contents of section .rodata: 400570 01000200 00000000 00000000 00000000 ................ 400580 6a69676e 65736870 61726d61 72000000 jigneshparmar... 400590 61646472 65737320 6f662073 74722064 address of str d 4005a0 6174613a 2570202c 20616464 72657373 ata:%p , address 4005b0 206f6620 73747220 76617269 61626c65 of str variable 4005c0 3a25700a 00 :%p.. 看起来是一种 Model 的方法,而不是 Query。我猜你在这里通过在现有查询对象上调用它的方式来使用它,你可能只是覆盖了它。

为什么不只是:

countDocuments()

答案 1 :(得分:1)

当我尝试实现分页时,我发现自己遇到了类似的问题。我想出的答案是在 merge 对象上使用 Query 函数。

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

答案 2 :(得分:1)

受到 Mathew 回答的启发:

我添加这个答案是因为我发现第二条和第三条指令不依赖于 MyModel 很重要,它们只依赖于 query 对象。

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

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