猫鼬返回空数组

时间:2020-06-24 07:30:41

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

我在Mongo有一个数据库,其中有2个收藏集,用户和广告系列。对于前者,我的所有请求(获取,发布,修补等)都可以正常工作。但是,我在广告系列方面遇到了问题。

我可以用邮递员创建一个新的广告系列,但不能“获取”这些广告系列。该请求显示成功,但返回一个空数组。

我将广告系列划分为: campaignController, ***模型, ***路线,

和一个用于处理用户和广告系列的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;

campaignController:

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
  });
});

campaignRoutes:

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;

知道我要去哪里哪里吗?

1 个答案:

答案 0 :(得分:1)

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

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