猫鼬:是否可以在数组类型的字段上使用填充到 return 只有 X 个该数组的元素?
Mongoose: Is it possible to use populate on a field of type array to return only X number of elements of that array?
我有这个型号:
const UserSchema = new Schema({
following: [
{
type: Schema.Types.ObjectId,
ref: "users",
},
],
});
module.exports = User = mongoose.model("users", UserSchema);
我想在 following
字段上使用 populate
,但是 return 只有该数组的前 5 个元素。
是否可以直接使用 populate 执行此操作?
我知道我最近可以在获取所有数组元素后进行此数组截断。但是,我正在做的是一个复杂的查询,我不想让它进一步复杂化。
谢谢。
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:
限制
如果你想获得 总共 5 following
而不管用户数量
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.
每个文档限制
如果您希望每个用户总共获得 5 个关注
告诉 Mongoose 执行单独查询的特殊选项
对于每个 User
以确保我们为每个用户获得 5 following
。
const users = await User.find().populate({
path: 'following',
options: { perDocumentLimit: 5 }
});
我有这个型号:
const UserSchema = new Schema({
following: [
{
type: Schema.Types.ObjectId,
ref: "users",
},
],
});
module.exports = User = mongoose.model("users", UserSchema);
我想在 following
字段上使用 populate
,但是 return 只有该数组的前 5 个元素。
是否可以直接使用 populate 执行此操作?
我知道我最近可以在获取所有数组元素后进行此数组截断。但是,我正在做的是一个复杂的查询,我不想让它进一步复杂化。
谢谢。
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:
限制
如果你想获得 总共 5 following
而不管用户数量
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.
每个文档限制
如果您希望每个用户总共获得 5 个关注
告诉 Mongoose 执行单独查询的特殊选项
对于每个 User
以确保我们为每个用户获得 5 following
。
const users = await User.find().populate({
path: 'following',
options: { perDocumentLimit: 5 }
});