【问题标题】:Mongoose returning empty array猫鼬返回空数组
【发布时间】:2020-06-25 12:56:37
【问题描述】:

我在 Mongo 中有一个数据库,其中包含 2 个集合、用户和活动。对于前者,我的所有请求(get、post、patch 等)都能正常工作。但是,我遇到了广告系列问题。

我可以在邮递员中创建一个新广告系列,但不能“获取”广告系列。请求看似成功,但返回一个空数组。

我将广告系列分为: 活动控制器, ***模型, ***路线,

还有一个 handlerFactory 来覆盖用户和活动。

handlerFactory:

exports.getAll = Model =>
  catchAsync(async (req, res, next) => {
    // To allow for nested GET reviews on tour (hack)
    let filter = {};
    if (req.params.campaignId) filter = { campaign: req.params.campaignId };

    const features = new APIFeatures(Model.find(filter), req.query)
      .filter()
      .sort()
      .limitFields()
      .paginate();
    // const doc = await features.query.explain();
    const doc = await features.query;

    // SEND RESPONSE
    console.log('-------', doc);
    res.status(200).json({
      status: 'success',
      results: doc.length,
      data: {
        data: doc
      }
    });
  });

活动模式:

const campaignSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Campaign name can not be empty!']
    },
    clientID: {
        type: String,
    },
    creator_id: {
        type: String,
    },
    budget: {
        type: Number,
        min: 100,
        required: [true, 'Campaign name can not be empty!']
    },
    startStatus: {
    type: String,
    enum: ['preStart', 'isStarted', 'preEnd'],
    default: 'preStart'
    },
    startDate: {
        type: Date,
    },
    createdAt: {
      type: Date,
      default: Date.now
    },
    updatedAt: {type: Date,
      default: Date.now
    },
    isDeleted: {
        type: Boolean,
        // required: [true, 'Must be true or false!']
        default: false
    },
    Priority: {
        type: Boolean,
        default: false,
    },
    location: {
        type: String,
        enum: ['Helsinki', 'Tallinn'],
        default: 'Helsinki'
    }
});

campaignSchema.pre('save', function(next) {
    if (!this.isModified('createdAt') || this.isNew) return next();

  this.updatedAt = Date.now() - 1000;
  next();
});

campaignSchema.pre(/^find/, function(next) {
  // this points to the current query
  this.find({ isDeleted: { $ne: false } });
  next();
});


const Campaign = mongoose.model('Campaign', campaignSchema);

module.exports = Campaign;

活动控制器:

exports.getAllCampaigns = factory.getAll(Campaign);
exports.getCampaign = factory.getOne(Campaign);
exports.createCampaign = factory.createOne(Campaign);
exports.updateCampaign = factory.updateOne(Campaign);
exports.deleteCampaign = factory.deleteOne(Campaign);

exports.getMe = (req, res, next) => {
  req.params.id = req.campaign.id;
  next();
};

exports.deleteCurrentCampaign = catchAsync(async (req, res, next) => {
  await User.findByIdAndUpdate(req.campaign.id, { active: false });

  res.status(204).json({
    status: 'success',
    data: null
  });
});

活动路线:

const router = express.Router();

router
  .route('/')
  .get(campaignController.getAllCampaigns)
  .post(
    authController.protect,
    authController.restrictTo('admin', 'super-admin'),
    campaignController.createCampaign
  );

router
  .route('/:id')
  .get(campaignController.getCampaign)
  .patch(
    authController.protect,
    authController.restrictTo('admin', 'super-admin'),
    campaignController.updateCampaign
  )
  .delete(
    authController.protect,
    authController.restrictTo('admin', 'super-admin'),
    campaignController.deleteCampaign
  );

module.exports = router;

知道我哪里出错了吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    所有代码看起来都不错,但可能有问题的是,您的集合不包含任何 isDeleted=true 的记录。

    因为在任何 find* 查询之前调用了campaignModel 中的“查找查询中间件”,它会找到所有 isDeleted != false 的文档。

    【讨论】:

      猜你喜欢
      • 2016-04-28
      • 2017-03-30
      • 2018-08-28
      • 2022-11-22
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      相关资源
      最近更新 更多