node.js - 如何使用 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 }
解决方案
推荐阅读
- python - 如何快速将值从一个数据帧复制到另一个数据帧
- c# - 将 ac# dll 中的类导入 C++ 应用程序
- directory - 使用 R 从列表中重命名目录中的文件
- qt - Qt 小部件没有收到 keyPressEvent
- javascript - 按对象名称打字稿对对象数组进行排序
- assert - 断言一个字符串包含某个值(如果没有,则测试失败)
- ios - 使用 MapKit 在地图上看不到当前位置
- javascript - 检测重定向并打开模式(弹出)
- c++ - 这个字符串加法是一个有效的表达式吗?
- c# - 如何在 StackLayout 中维护 Xamarin Forms 控件的纵横比