[英]Check if ID exist in related mongodb collection with mongoose
I have a "Drinkers" model and a "Sodas" model which is "related" - a drinker can have drunk X amount of sodas.我有一个“饮酒者”模型和一个“相关”的“苏打水”模型——一个饮酒者可以喝 X 量的苏打水。
The route to get the data is this获取数据的路径是这样的
router.get('/all/:drinkerId', sodasController.getAllSodasFromDrinker)
In my sodasController
, is there a way to check if :drinkerId
exists in the "Drinkers" collection and if not return an error that the drinker doesn't exist, without having to require the drinkersController
in the sodasController
.在我的
sodasController
,是有办法检查:drinkerId
存在于“喝酒”的收集,如果不返回酒量不存在的错误,而不必要求drinkersController
在sodasController
。
Right now getAllSodasFromDrinker
looks like this现在
getAllSodasFromDrinker
看起来像这样
const Sodas = require("../models/sodas.model");
exports.getAllSodasFromDrinker = async (req, res, next) => {
try {
const id = req.params.drinkerId;
if (id.match(/^[0-9a-fA-F]{24}$/)) {
await Sodas.find({ drinker: id }).exec((err, drinkerItem) => {
if (err) {
return next(err);
}
res.json({ data: drinkerItem });
});
} else {
return next("ID is in the wrong format");
}
} catch (error) {
return next(error);
}
};
In that function, I want to check if a user exists with the applied ID.在该函数中,我想检查是否存在具有应用 ID 的用户。
I want to avoid having to const Drinkers = require("../models/drinkers.model")
in the sodasController我想避免在 sodasController 中
const Drinkers = require("../models/drinkers.model")
drinkers.model const Drinkers = require("../models/drinkers.model")
The Drinkers model:饮水机模型:
const Schema = mongoose.Schema;
const drinkersSchema = new Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
sodas: {
type: Schema.Types.ObjectId,
ref: "Sodas",
},
},
{ timestamps: true }
);
The Sodas model苏打水模型
const Schema = mongoose.Schema;
const sodaSchema = new Schema(
{
name: {
type: String,
required: true,
},
drinker: {
type: Schema.Types.ObjectId,
ref: "Drinkers",
},
},
{ timestamps: true }
);
I would add a middleware function which validates if the drinkerId
exists.我会添加一个中间件函数来验证
drinkerId
存在。 If it exists, you can continue to the controller.如果存在,您可以继续使用控制器。 If not, then you should throw a 404 error.
如果没有,那么你应该抛出 404 错误。
Your route:您的路线:
router.get(
'/all/:drinkerId',
drinkerMiddleware.exists,
sodasController.getAllSodasFromDrinker
);
drinkerMiddleware:饮酒者中间件:
exports.exists = async (req, res, next) => {
try {
const drinker await Drinker.find({ drinker: req.params.drinkerId }).exec();
if (!drinker) {
return next("Drinker not found.");
}
return next();
} catch (error) {
return next(error);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.