mongodb 如何将对象数组添加到在ReactJs中有多个文档的mongoose数据库中

uqdfh47h  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(121)

我正在向后端传递axios请求,按顺序,req.body正在传递一个对象数组newItemsObj我正在尝试将这些对象数组保存到模式为NewItemsData的mongoose数据库中此数据模型引用另一个数据模型MoneyInData,但在尝试保存到NewItemsData模型时,我收到一个ValidationError,需要几个字段,请我做错了什么,我怎么能有效地保存这个数组的对象在数据库中。这里的代码只是片段,使它很容易理解。请我需要你的帮助,谢谢。

//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

字符串

5gfr0r5j

5gfr0r5j1#

如果newItemApiList是数组,则尝试:

const addNewItems = await NewItemsData.create(newItemsObj.newItemApiList);

字符串
或者使用扩展语法,如果你喜欢的话

const addNewItems = await NewItemsData.create([...newItemsObj.newItemApiList]);

相关问题