I'm trying to add data to an array via a post request with mongoose. I can find the correct data with Model.find(). But I am not sure how to add data to "guests" array on each post request. For example I would like the guests to return something like this (a guest can be added with a post request):
guests: [{
id: 12412,
naam: 'John',
email: '[email protected]'
},
{
id: 12412,
naam: 'John',
email: '[email protected]'
}
]
I can find the correct "eventid" (code below) with the dataset but not sure how to add data to "guests".
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const bodyParser = require("body-parser");
var app = express();
var schemaName = new Schema({
eventid: String,
evenementnaam: String,
locatie: String,
datum: String,
tijd: String,
beschrijving: String,
naam: String,
email: String,
telefoon: String,
image: String,
time: Number,
guests: [{
userid: Number,
naam: String,
email: String
}] // WANT TO ADD TO THIS ARRAY
}, {
collection: 'evenementen'
});
var Model = mongoose.model('Model', schemaName);
mongoose.connect('mongodb+srv://db');
app.post('/addguest', function(req, res) {
req.body.eventid;
mongoose.connection.on('open', function(err, doc) {
console.log("connection established");
mongoose.connection.db.collection('evenementen', function(err, docs) {
Model.find({
'eventid': req.body.eventid;
}, function(err, result) {
if (err) throw err;
if (result) {
// ADD GUEST TO GUESTS ARRAY
} else {
res.send(JSON.stringify({
error: 'Error'
}))
}
})
});
});
});
Update #1 The following test is not adding anything to "guests"
mongoose.connection.on('open', function (err, doc) {
console.log("connection established");
var newdata = [{
userid: 21424,
naam: 'John Test',
email: '[email protected]'
}];
mongoose.connection.db.collection('evenementen', function (err, docs) {
Model.findOne({
'eventid': 'srA4aqC'
}, function (err, result) {
if (err) throw err;
if (result) {
console.log(result);
Model.update({
'eventid': 'srA4aqC'
}, {
'$push': {
'guests': {
'$each': newdata
}
}
})
console.log('succes');
} else {
res.send(JSON.stringify({
error: 'Error'
}))
}
})
});
});
Update 2 Need to remove the ' ' from a few elements. Correct code:
$push: {
guests: {
$each: newdata
}
}