【问题标题】:Mongoose populate with paginationMongoose 使用分页填充
【发布时间】:2020-12-01 15:44:54
【问题描述】:

尝试在我填充的查询上实现分页。我成功填充了猫鼬填充,但限制或跳过不起作用。还尝试了 mongoose-paginate 库,分页工作但人口没有。 作为输出,我只需要按用户 ID 分页的任务数组。谢谢。

用户架构:

var mongoosePaginate = require('mongoose-paginate');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    unique: true,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  uavs: [uavSchema],
  missions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Mission' }],
});

userSchema.plugin(mongoosePaginate);

这有效,但限制或跳过无效

const getMissions = async (_id) => {
  let missions = [];
  try {
    await User.findOne({ _id: _id })
      .lean()
      .populate('missions')
      .then((usr) => {
        console.log(usr);
        Object.assign(missions, usr.missions);
      });
    return { success: true, missions };
  } catch (err) {
    return { success: false, err };
  }
};

output when using mongoose populate

然后尝试使用 mongoose-paginate

const getMissions = async (_id) => {
  try {
    var options = {
      populate: 'missions',
      page: 1,
      limit: 4,
      lean: true,
    };
    await User.paginate({ _id: _id }, options, function (err, result) {
      console.log(result);
    });
  } catch (err) {
    console.log(err);
  }
};

output when using mongoose-paginate

【问题讨论】:

    标签: node.js mongodb express mongoose pagination


    【解决方案1】:

    解决方案 - 搜索任务集合

    const getMissions = async (_id, page, limit) => {
      try {
        let missions = {};
        var options = {
          page,
          limit,
          lean: true,
        };
        await Mission.paginate({ _owner: _id }, options, function (err, result) {
          Object.assign(missions, result);
        });
        return { success: true, missions };
      } catch (err) {
        return { success: false, err };
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 2014-10-03
      • 2017-10-29
      • 2020-05-02
      • 2019-01-31
      • 2019-06-25
      相关资源
      最近更新 更多