我正在将AXIOS请求传递到后端,换句话说,请求主体在这里传递对象数组newItemsObj
我正try 将这些对象数组保存到具有架构NewItemsData
的Mongoose数据库中.此数据模型引用另一个数据模型MoneyInData
,但在try 保存到NewItemsData模型时,我收到了一个ValidationError,指出需要几个字段,请注意,我可能做错了什么,以及如何在数据库中有效地保存此对象array.这里的代码只是很容易理解的代码片段.谢谢,我需要你的帮助.
//NewItemsData Model
const mongoose = require('mongoose');
const MoneyInData = require('./MoneyInData');
const newItemsSchema = new mongoose.Schema({
productName:{
type: String,
required: true
},
sellingPriceOfTotal:{
type: String,
required: true
},
quantityCount: {
type: Number
},
unitOfQuantity:{
type: String
},
sellingPrice:{
type: Number,
required:true
},
sales:{
type: mongoose.Schema.Types.ObjectId,
ref: 'MoneyInData'
}
})
module.exports = mongoose.model('NewItemsData', newItemsSchema);
//MoneyInData Model
const mongoose = require ('mongoose')
const moneyInDataSchema = new mongoose.Schema({
totalAmountIn:{
type: String,
required: true
},
amountRecieved:{
type: String,
required: true
},
balanceDue: {
type: Number
},
itemDescription:{
type: String
},
modeOfPayment:{
type: String,
required:true
}
})
module.exports = mongoose.model('MoneyInData', moneyInDataSchema)
//Create Method for Writing to the database
// @desc post newItems
// @route POST /newItems
// @access Private
const createNewItems = asyncHandler(async (req, res) => {
const newItemsObj = req.body
console.log(newItemsObj)
if (!newItemsObj) {
return res.status(400).json({ message: 'All fields are required' })
}
const addNewItems = await NewItemsData.create(newItemsObj);
if (addNewItems) {//created
res.status(201).json({ message: 'New Item Recorded' })
console.log(addNewItems)
console.log(newItemsObj)
} else {
res.status(400).json({ message: 'Invalid Item' })
}
})
//sample array of Object data contained in newItemsObj variable
{
newItemApiList: [
{
productName: 'molly',
sellingPriceOfTotal: 17400,
quantityCount: 3,
unitOfQuantity: 'grams',
sellingPrice: '5800'
},
{
productName: 'group',
sellingPriceOfTotal: 9000,
quantityCount: 2,
unitOfQuantity: 'cm',
sellingPrice: '4500'
}
]
}
//Error message:
ValidationError: NewItemsData validation failed: sellingPrice: Path `sellingPrice` is required., sellingPriceOfTotal: Path `sellingPriceOfTotal` is required., productName: Path `productName` is required.
at Document.invalidate (C:\Users\USER\Desktop\bussiness-books\server\node_modules\mongoose\lib\document.js:3183:32)
at C:\Users\USER\Desktop\bussiness-books\server\node_modules\mongoose\lib\document.js:2976:17
at C:\Users\USER\Desktop\bussiness-books\server\node_modules\mongoose\lib\schematype.js:1368:9
at process.processTicksAndRejections (node:internal/process/task_queues:77:11)
GET/newItems
GET/newItems