简体   繁体   中英

Updating with mongoose using dynamic path

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.

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

try this?:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM