我正试图通过mongoose的post请求将数据添加到数组中。我可以用Model.find()找到正确的数据。但我不知道如何在每个post请求上向“guests”数组添加数据。例如,我希望来宾返回这样的内容(可以在post请求中添加来宾):
guests: [{
id: 12412,
naam: 'John',
email: 'john@doe.com'
},
{
id: 12412,
naam: 'John',
email: 'john@doe.com'
}
]
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'
}))
}
})
});
});
});
更新#1
下面的测试没有给“guests”添加任何内容
mongoose.connection.on('open', function (err, doc) {
console.log("connection established");
var newdata = [{
userid: 21424,
naam: 'John Test',
email: 'test@test.com'
}];
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'
}))
}
})
});
});
需要从几个元素中删除''。正确代码:
$push: {
guests: {
$each: newdata
}
}