0

My model looks like this:

var eventSchema = new mongoose.Schema({
    'eventTitle': String,
    'location': String,
    'startDate': String,
    'endDate': String,
    'startTime': String,
    'endTime': String,
    'createdBy': mongoose.Schema.Types.ObjectId, // Here we will store the _ID from the user EOSP.
    'attendants': {
        'seekers': [mongoose.Schema.Types.ObjectId],
        'employers': [
        //     {
        //         'id': mongoose.Schema.Types.ObjectId,
        //         'boothVisits': Number,
        //     }
        ],
    },
    'isFinished': {'type': Boolean, 'default': false},
    'uploadedResumes': Number,
    'downloadedResumes': Number,
});

And this is my code:

Event.findByIdAndUpdate(eventId, {$inc:{`attendants.employers[${req.params._id}].boothVisits`: 1}, $upsert: true});

So the problem is, if I try to do this ^^^^^ my node yells at me saying:

/home/alex/Documents/Projects/ontario-job-portal/routes/employer.js:58 Event.findByIdAndUpdate(eventId, {$inc: {attendants.employers[${req.params._id}].boothVisits: 1}, $upsert: true}); ^^^^^^^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected template string

But if I try to do this:

const path = `attendants.employers[${req.params._id}].boothVisits`;
Event.findByIdAndUpdate(eventId, {$inc: {path: 1}, $upsert: true});

My IDE tells me that the path variable is actually not used in the query. How can I get around it? I really need the id to be dynamic.

Alex Ironside
  • 4,658
  • 11
  • 59
  • 119
  • Try `Event.findByIdAndUpdate(eventId, {$inc:{attendants.employers.[req.params._id].boothVisits: 1}, $upsert: true});` – s7vr Oct 16 '18 at 12:39
  • I like the idea, but this tells me `Event.findByIdAndUpdate(eventId, {$inc:{attendants.employers.[req.params._id].boothVisits: 1}, $upsert: true}); ^ SyntaxError: Unexpected token .` – Alex Ironside Oct 16 '18 at 12:52
  • 1
    You're looking for creating object with dynamic key. Take a look at this answer: https://stackoverflow.com/questions/19837916/creating-object-with-dynamic-keys – willie17 Oct 16 '18 at 13:19
  • @willie17 that was it! Would you like to add an answer? – Alex Ironside Oct 16 '18 at 15:11

2 Answers2

1

Try with below query

Tested on mongo GUI.

const mongoose = require('mongoose');


db.getCollection('content')
  .update({
    'attendants.employers.id': mongoose.Types.ObjectId((req.params._id)
    }, {
    $inc: { "attendants.employers.$.boothVisits": 1 }
  })
IftekharDani
  • 3,619
  • 1
  • 16
  • 21
0

try this?:

Event.findByIdAndUpdate(eventId,
     {
        $inc: { 'attendants.employers.boothVisits': {$in: [req.params._id] }: 1}, 
        $upsert: true
     });
shuk
  • 1,745
  • 1
  • 14
  • 25
  • This tells me `/home/alex/Documents/Projects/ontario-job-portal/routes/employer.js:58 Event.findByIdAndUpdate(eventId, {$inc: { 'attendants.employers.boothVisits': {$in: [req.params._id] }: 1},$upsert: true}); ^ SyntaxError: Unexpected token : ` – Alex Ironside Oct 16 '18 at 12:52