Mongoose架构-强制将一个属性作为同一架构上不同属性的现有值(枚举

nuypyhwy  于 2022-10-22  发布在  Go
关注(0)|答案(1)|浏览(146)

我有这样的方案:

  1. const schema = new Schema({
  2. deviceName: { type: String, required: true, unique: true},
  3. category: { type: String, enum: DEVICE_CATEGORIES, required: true },
  4. incompatibleWithDevices: [String]
  5. });
  6. const DeviceModel = model(
  7. "Device",
  8. schema
  9. );

incompatibleDevices应该是相关设备无法使用的其他设备的列表(按设备名称)。因此,该数组应该只接受数据库中实际存在的设备名称。出于业务逻辑的目的,我在这里不能有一对多关系。
我曾想过以某种方式将当前存在的所有设备名称都枚举起来,但由于这会随着设备的添加/删除而不断变化,所以我想不出一个方法来做到这一点。
有谁知道如何做到这一点吗?也许是带有定制验证器的东西?
提前感谢,如有任何帮助,不胜感激!

56lgkhnf

56lgkhnf1#

在创建新的Device文档之前,您可以直接在后端逻辑中添加验证,以检查您要发送的设备是否存在于数据库中。
您可以使用$in运算符:

  1. const createDevice = async (req, res) => {
  2. try {
  3. const { deviceName, category, incompatibleWithDevices} = req.body;
  4. const incompatibleDevices = await Devices.find({ deviceName: { $in incompatibleWithDevices }});
  5. // Here, you do the validation if some deviceName are maybe invalid.
  6. // At least one device will be invalid if returned array is not the same
  7. // size as the input array.
  8. if (incompatibleDevices.length !== incompatibleWithDevices.length) {
  9. return res.status(400).json({ sucess: false });
  10. }
  11. // Here you can add the logic that creates the new device since
  12. // all inputs are valid.
  13. } catch (error) {
  14. return res.status(400).json({ success: false })
  15. }
  16. }
展开查看全部

相关问题