首页 > 解决方案 > 插入未关联的猫鼬表

问题描述

对于猫鼬的帮助,我将不胜感激。我有表用户、订单和公司。当我创建订单或公司表时,我通过虚拟外键将它们与用户表相关联。

我的问题是我想通过带有数据来源、目的地的表单提交/创建订单,当我输入公司(如果我可能插入公司 ID 或名称)时,它与公司表相关联,并且还插入到订单下的公司表中 {}

我应该如何制作这个模型或路线?

非常感谢您的帮助。

订购型号:

const mongoose = require('mongoose')

const orderSchema = new mongoose.Schema({
    origin: {
        type: String
    },
    destination: {
        type: String
    },
????company:{
        // type: String
        // type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Company'
    },
    completed: {
        type: Boolean,
        default: false
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
}, {
    timestamps: true
})

const Order = mongoose.model('Order', orderSchema);

module.exports = Order;

公司型号:

const mongoose = require('mongoose')
const Order = require("./order");

const companySchema = new mongoose.Schema({
    oib: {
        type: Number
    },
    name: {
        type: String
    },
    address:{
        type: String
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    drivers: [
        {
            driver: {
                type: Number
            }
    }
    ],
    orders: [
        {
            order: {
                type: Number
            }
    }
]
}, {
    timestamps: true
})

//Orders Foreign key
companySchema.virtual("order", {
    ref: "Order",
    localField: "_id",
    foreignField: "company",
  });

const Company = mongoose.model('Company', companySchema);

module.exports = Company; 

标签: javascriptnode.jsmongodbmongoose

解决方案


我希望我理解得很好。几年前我也遇到过类似的问题。我用 Save/Validate Hooks Doc 解决了我的问题:Save/Validate Hooks in https://mongoosejs.com/docs/middleware.html#order

基本上,在预验证功能中,我检查了您案例中的对象order是否具有objectId作为归档company值或另一个对象或带有 company 的字符串name

在 的情况下objectId,我什么也没改变。在名称的情况下(在我的情况下,我有一个(名称、地址等)的子对象,我启动了必要的逻辑来查找或插入丢失的数据,并用company新创建或获取的 ID 替换该字段。

所以后面的验证和保存可能会成功。


推荐阅读