mongodb - 如何在猫鼬中使用 $lt
问题描述
我正在尝试获取报告数量少于用户总数 10% 的帖子。目前,每个帖子的默认报告长度为 0。
const Users = await User.find();
// console.log(Users.length);
const lt = Math.ceil(0.1 * Users.length);
// console.log(Math.ceil(lt));
const posts = await Post.find({
reportsLength: { $lt: lt },
type: req.params.type,
})
这是帖子模型
const postSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
type: {
type: String,
required: true,
},
reports: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
},
],
reportsLength: {
type: Number,
default: 0,
},
},
{ timestamps: true }
);
解决方案
你可以这样做:
const numOfUsers = await User.countDocuments();
const lt = Math.ceil(0.1 * numOfUsers);
const posts = await Post.find({
reportsLength: { $lt: lt },
type: req.params.type,
})
推荐阅读
- javascript - 姜戈。如何为表单中的隐藏/显示字段设置条件以使其依赖于后端?
- java - 为什么没有跟踪 AspectJ 之前和之后的日志?
- kubernetes - 自动驱逐 Kubernetes 中未使用的部署
- python - 无法在 python 中安装 PyAudio
- python - driver.find_element_by_css_selector 在页面末尾运行缓慢
- nginx - 无法在同一 Ubuntu 服务器上获取第二个 Nginx 站点以正常工作并完成 acme 挑战
- javascript - 5秒后Keycloak javascript示例注销
- c++ - 如何让编译器用尽可能少的代码对奇数多态结构进行偏移计算?
- jquery - 使用 ng-repeat 的指令双向绑定未绑定回模型
- ios - 图表实时更新图表 - 数据记录在一个 VC 并绘制在另一个