I am developing an application in which I need to send an array with the time and amount of food. When I print the console log on the front (vuejs and axios), I can see the array with the correct information, but when I send that array to the back (express and mongoose) it arrives as Undefined. I am providing below the front my functions and the code of my back.
I`m using MongoDB as database.
Could you please help me?
FRONTEND: (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);
Express code:
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');
}
});
I expected to see my Meals array with time and quantity, but I`m getting this on my terminal
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 }