首页 > 解决方案 > 如何使用 express.js 和 axios 将数组插入到 mongodb

问题描述

我正在开发一个应用程序,我需要在其中发送一个包含食物时间和数量的数组。当我在前面(vuejs 和 axios)打印控制台日志时,我可以看到包含正确信息的数组,但是当我将该数组发送到后面(express 和 mongoose)时,它以未定义的形式到达。我在前面提供了我的功能和后面的代码。

我正在使用 MongoDB 作为数据库。

请你帮助我好吗?

前端:(vuejs)

addMealList() {
        if (this.editedIndex > -1) {
          Object.assign(this.mealList[this.editedIndex], this.mealInformations);
          console.log(this.mealList);
        } else {
          this.mealList.push(this.mealInformations);
          console.log(this.mealList);
        }
        this.close()
        },

        addToAPI() {
            // console.log(this.mealList);

            axios.post(`${this.serverUrl}devices/register`, this.mealList)
                .then((res) => {
                console.log(this.mealList);
                console.log(res.data);
                })
                .catch((error) => {
                console.log(error);
                });
        },
```

BACKEND: (mongoose and express)

Schema File:

```
const mongoose = require('mongoose');

const mealSchema = new mongoose.Schema({
  time: {
    type: String,
    required: true
  },
  quantity: {
    type: String,
    required: true
  }
});

const deviceSchema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  mealList: [mealSchema],
  creation_information: {
    date: {
        type: Date,
        default: Date.now
    },
    by: {
      type: String,
      required: true
    }
  }

}, { collection : 'device' });

module.exports = mongoose.model('device', deviceSchema);

快递代码:

router.post('/register', (req, res) => { 
    console.log(req.body.mealList);
    console.log(req.user);
    const device = new Device({
        _id: new mongoose.Types.ObjectId(),
        mealList: [ req.body.mealList ],
        creation_information: {by: req.user._id}
    });
    console.log(device);
if (device.mealList && device.mealList.length) {
        device.save().then(result =>{
            console.log(result);
            res.status(201).json({
                message: "Hadling POST requests to device",
                createdDevice: result
            }); 

        })
        .catch(err =>{
            console.log(err);
            res.status(500).json({
                error: err
            })
        });
      }else {
          console.log('array is empty');
      }

});

我希望看到我的 Meals 数组的时间和数量,但我在我的终端上得到了这个

undefined
{ _id: 5cfbde0d5bd9cd0e168f14cf,
  mealList: [ undefined ],
  creation_information: { by: 'Lorena Meyas', date: 2019-06-08T16:10:53.756Z } }
{ _id: 5cfbde0d5bd9cd0e168f14cf,
  mealList: [ undefined ],
  creation_information: { by: 'Lorena Meyas', date: 2019-06-08T16:10:53.756Z },
  __v: 0 }

标签: node.jsmongodbexpressvue.jsaxios

解决方案


推荐阅读