[英]Trying to post array in my mongodb collection from POST API in node.js using mongoose and express
這是我的訂單 model 。
const Order = mongoose.model('Order', new mongoose.Schema({
saleprice: {type: Number},
discount: {type: Number},
products : [{
type: productSchema
}]
}));
這是我的產品 model
const productSchema = new mongoose.Schema({
name: {type: String, required: true},
price: {type: Number, required: true},
category: {type: String, required: true}
});
現在我想在 API 調用后以單個訂單發布多個產品; 目前使用這種方法,但這不適用於 arrays。 如何僅通過以 JSON 格式發送多個 productId 來添加多個產品。
router.post('/', async(req, res) =>{
const product = await Product.findById(req.body.productId);
if(!product)
return res.status(400).send('Invalid product.');
const order =new Order({
saleprice: "790",
discount: "100",
products: [{
_id: product._id,
name: product.name,
price: (product.price).toString(),
category: product.category
}]
});
await order.save();
res.send(order);
});
您必須以模塊化的方式考慮它並逐步處理它。
您目前正在嘗試一次完成所有操作。 把它分成幾塊。
ZCCADCDEDB567ABAE643E15DCF0974E503Z 有一個名為 populate() 的方法,可以讓您參考其他 collections 中的文檔。
填充是自動將文檔中的指定路徑替換為其他集合中的文檔的過程。 我們可以填充單個文檔、多個文檔、普通 object、多個普通對象或從查詢返回的所有對象。
這是一個例子:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const Person = mongoose.model('Person', personSchema);
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
從示例中您可以看到您的方法不正確,因為您沒有在 Order 和 Product 之間設置引用。
您訂購的架構可以設置對產品的引用,如下所示:
...
products : [{
type: Schema.Types.ObjectId, ref: 'Product'
}]
...
上面的代碼定義了Order和Product數據庫模式之間的關聯。 就像我在開頭提到的那樣,您必須采用模塊化方法。 根據我對您的項目的了解,您首先創建產品,然后客戶為每個產品創建一個訂單。 您必須創建一個產品。 完成此操作后,您可以在創建訂單時按 Id 引用特定產品。 像這樣:
...
const order =new Order({
saleprice: "790",
discount: "100",
products: req.body.productId
});
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.