In the below user schema there is a foobar.events
field, an array of hashes, that I am trying to push new hashes (that are received from an API POST request) to.
var userSchema = mongoose.Schema({
foobar: {
id : String,
token : String,
email : String,
name : String,
events : [{
action : String,
timestamp : Date,
user_xid : String,
type : {type: String},
event_xid : String
}]
}
});
And here is the logic for that Express route:
app.post('/foobar/post', function(req, res) {
var jb_user_xid = req.body['events'][0]['user_xid'];
var jb_timestamp = req.body['events'][0]['timestamp'];
var jb_action = req.body['events'][0]['action'];
var jb_type = req.body['events'][0]['type'];
var jb_event_xid = req.body['events'][0]['event_xid'];
User.findOne({'foobar.id':jb_user_xid}, function(err, user) {
user.foobar.events.push({
user_xid: jb_user_xid,
timestamp: jb_timestamp,
action: jb_action,
type: jb_type,
event_xid: jb_event_xid
});
user.save(function(err) {
if (err){
console.log("Error on save: " + err);
}
else {
console.log("Save successful");
}
});
});
res.writeHead(200);
res.end();
return;
});
The find
and save
execute successfully, but the hash itself isn't saved to the database, as shown in the logfile:
Mongoose: users.update({ _id: ObjectId("53f7d23e432de20200970c10") }) { '$inc': { __v: 1 }, '$pushAll': { 'foobar.events': [ '[object Object]' ] } } {}
And here is what the entry looks like within MongoLab:
{
"__v": 11,
"_id": {
"$oid": "53f7d23e432de202970c10"
},
"foobar": {
"events": [
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]"
],
"id": "aguxwNqb_Xg87buMWiw",
"name": "Test User",
"token": "W3AjaI7_iOWilcKRpmx"
}
}
Question: How do I save the actual contents from the API hash to a new hash within the foobar.events
array?
As a side note, this is what is returned in req.body
from the API:
{ events:
[ { action: 'updation',
timestamp: 1408846680,
user_xid: 'aguxwNqb_Xg87buMyP6Wiw',
type: 'move',
event_xid: 'vhAkgg1XwQvLynAkkCc8Iw' } ],
notification_timestamp: 1408846680 }