我试图通过猫鼬的发布请求将数据添加到数组。我可以使用Model.find()找到正确的数据。但是我不确定如何在每个发布请求中向“来宾”数组添加数据。例如,我希望来宾返回这样的内容(可以向来宾添加发帖请求):
guests: [{
id: 12412,
naam: 'John',
email: 'john@doe.com'
},
{
id: 12412,
naam: 'John',
email: 'john@doe.com'
}
]
我可以在数据集中找到正确的“ eventid”(下面的代码),但不确定如何将数据添加到“ 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'
}))
}
})
});
});
});
更新#1 以下测试未向“来宾”添加任何内容
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'
}))
}
})
});
});
更新2 需要从一些元素中删除“”。正确的代码:
$push: {
guests: {
$each: newdata
}
}
答案 0 :(得分:2)
首先,如果您的CURRENT_INTERSTITIAL_NUMBER = 2
PRESENT_INTERSTITIAL_NUMBER = 4
是唯一的,则需要将eventid
修改为Model.find()
,这样会好得多,然后可以使用{{3} },像这样:
Model.findOne()
但是,如果您有一个这样的来宾值,这将起作用:
if (result) {
Model.update({'eventid': req.body.eventid}, {'$push': {'guests': result}})
}
但是您在数组中有{
userid: Number,
naam: String,
email: String
}
,因此还需要使用guests
运算符:
$each