如何在MERN堆栈中存储数据数组

时间:2020-09-01 16:30:09

标签: javascript node.js arrays mern

我对MERN堆栈非常陌生,我试图在集合中的数组中插入数据。但这并没有完全插入。我尝试过使用for循环,但是执行时,它只是从循环中获取第一个值

代码: MyModel.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const mySchema = new Schema({
     No: { type: String, required: true, unique : true },
     details:{
         sl: { type: [String], required: true, unique : false},
         item: {type: [String], required: false},
         total: {type: String, required: true}
     }
})
module.exports = mongoose.model('detailsCollection', mySchema)

MyController.js

const Object = require('../models/MyModel')
insertData = (req, res) => {
    for(let i = 1; i<=5; i++){
        const Data = {
               No: '1001',
               details: {
                   sl: i,
                   item: 'ABC',
                   total: i * 1000
               }
         }
         Object.create(Data)
         .then(user => {
            res.json({ status: 'Data inserted!' })
         })
         .catch(err => {
             res.send('error: ' + err)
         })
    }
}

我想要这样的数据库中的数据:

No : "1001"
details:
   sl : 
     0: "1"
     1: "2"
     2: "3"
     3: "4"
     4: "5"
   item:
     0: "ABC"
     1: "ABC"
     2: "ABC"
     3: "ABC"
     4: "ABC"
   total:
     0: "1000"
     1: "2000"
     2: "3000"
     3: "4000"
     4: "5000"

但是我当前的输出是:

No : "1001"
details:
   sl : 
     0: "1"
   item:
     0: "ABC"
   total:
     0: "1000"

0 个答案:

没有答案
相关问题