首页 > 解决方案 > 如何在猫鼬中使用 $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 }
);

标签: mongodbexpressmongoose

解决方案


你可以这样做:

const numOfUsers = await User.countDocuments();
const lt = Math.ceil(0.1 * numOfUsers);
const posts = await Post.find({
    reportsLength: { $lt: lt },
    type: req.params.type,
})

推荐阅读