1

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
        }
}

1 Answer 1

4

First if your eventid is unique the you will need to modify Model.find() to Model.findOne() which will be much much better and then to update an array field you can use $push operator like this:

if (result) {
    Model.update({'eventid': req.body.eventid}, {'$push': {'guests': result}})
}

However, this will do the work if you have one guest value like this:

{
    userid: Number,
    naam: String,
    email: String
}

but you have guests in an array, so you need to use $each operator as well:

if (result) {
    Model.update({'eventid': req.body.eventid}, {'$push': {'guests': {'$each': result}}})
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is not adding new items to the array unfortunately. See #update1.
The problem was in using the quotation marks. Should have been $push instead of '$push'. Same for guests and $each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.