称为
Restaurant
的模式包含isLive
标志。
如何仅将包含isLive
标志的餐厅退回true
?
我不想在每个查询或每个聚合中都检查isLive
,如下所示:
exports.getRestaurants = async (req, res) => {
const restaurants = await Restaurant.getAllRestaurants();
if (!restaurants) return next();
const liveRestaurants = restaurants.filter(restaurant => restaurant.isLive);
res.status(200).json({ restaurants: liveRestaurants });
};
我想做的是将与Restaurant
架构相关的每个操作过滤为isLive = true
我试图使用猫鼬钩子,但我不知道如何基于isLive标志返回数据。
restaurantSchema.pre('aggregate', function(next) {
console.log('pre aggregate');
// Return data based on the isLive flag,, is it possible?
next();
});
因此,是否可以使用钩子基于isLive
标志返回值?或任何其他方式可以解决我的问题?
我建议您在模型上使用find方法:
exports.getRestaurants = async (req, res) => {
const liveRestaurants = await Restaurant.find(name: 'isLive', true);
if (!liveRestaurants) return next();
res.status(200).json({ restaurants: liveRestaurants });
};
您可以在MongoDB中创建database view并将您的isLive
添加为过滤条件。
Restaurant.db.createCollection('liveRestaurants', {
viewOn: 'restaurants',
pipeline: [{ $match: { isLive: true } }]
});
然后您需要使用相同模式的另一个模型:
let Restaurant = mongoose.model('Restaurant', restaurantSchema);
let LiveRestaurant = mongoose.model('liveRestaurants', restaurantSchema, 'liveRestaurants');
并且您可以以与查询常规模型相同的方式查询只读模型,但它只会返回经过过滤的餐馆:
let result = await LiveRestaurant.find();
是可以的。
您可以在架构上创建通用的预钩,如下所示:
const mongoose = require("mongoose");
const restaurantSchema = new mongoose.Schema({
name: String,
isLive: Boolean
});
restaurantSchema.pre(/^find/, function(next) {
this.find({ isLive: true });
next();
});
module.exports = mongoose.model("Restaurant", restaurantSchema);
现在所有查找方法都将使用此钩子,仅将使用isLive=true
检索餐馆。
测试:
我们有这3家餐厅:
[
{
"_id" : ObjectId("5e0caa0b606f3e2b24b2a96e"),
"name" : "Restaurant 1",
"isLive" : true,
},
{
"_id" : ObjectId("5e0caa11606f3e2b24b2a96f"),
"name" : "Restaurant 2",
"isLive" : false,
},
{
"_id" : ObjectId("5e0caa17606f3e2b24b2a970"),
"name" : "Restaurant 3",
"isLive" : true,
}
]
当我们像这样使用Restaurant.find({})
时:
const Restaurant = require("../models/restaurant");
router.get("/restaurant", async (req, res) => {
const result = await Restaurant.find({});
res.send(result);
});
非活动餐厅2将不会被检索,结果将是:
[
{
"_id": "5e0caa0b606f3e2b24b2a96e",
"name": "Restaurant 1",
"isLive": true
},
{
"_id": "5e0caa17606f3e2b24b2a970",
"name": "Restaurant 3",
"isLive": true
}
]
这也将用于其他与查找相关的查询。