如何设置创建新文档并将新文档存储在另一个文档的数组字段中的路由



我正在尝试创建一个库存应用程序。我想要这样一种情况,即对特定产品下达的每个订单都存储在产品库存文档的数组中。我有一个产品库存架构和订单架构。

// productInventory Schema
const ProductInventorySchema = new mongoose.Schema({

name : String,
description : String, 
price:Number,
quantity :Number,
supplier : String, 
taxable : Boolean,
orders: {
type: Schema.Types.ObjectId,
ref: "Orders",
required: true
},

},{timestamps:true});

module.exports = mongoose.model('inventory', ProductInventorySchema)
// Order Schema
const OrderSchema = new mongoose.Schema({

name : String,
quantity: Number,,
issuedBy : String,
collectedBy: String,
department : String,
},{timestamps:true});

module.exports = mongoose.model('order', OrderSchema)

我的策略是这样的:将特定产品上的每个订单附加到产品库存,这样,我可以做几件事,例如计算总订单数量并从产品库存数量中减去,我还可以查询与每个产品库存相关的所有订单。

我的挑战基本上是编写一个代码来创建新订单,然后将其附加到选定的 ProductInventory 中,最后将其作为 Array 存储在 ProductInventory 文档中。

我知道我最好的选择之一是使用猫鼬的填充 API,但似乎无法弄清楚如何为所需路由编写代码

您的ProductInventorySchema架构应如下所示:

const ProductInventorySchema = new mongoose.Schema({
name : String,
description : String, 
price:Number,
quantity :Number,
supplier : String, 
taxable : Boolean,
orders: [{
type: Schema.Types.ObjectId,
ref: "orders",
required: true
}],
},{timestamps:true});

示例终结点:

const Inventory = require('./productInventorySchema.js');
const Order = require('./orderSchema.js');
app.post('/order', async (req, res) => {
const { name, quantity, issuedBy, collectedBy, department, inventoryId } = req.body;
const order = await Order.create({
name,
quantity,
issuedBy,
collectedBy,
department
});
const inventory = await Inventory.find({ _id: inventoryId });
inventory.orders.push(order._id);
await inventory.save();
res.send('Order created');
});

上面的代码没有经过测试。这只是为了给出一个如何实现它的想法。代码可以改进。

最新更新