使用动态路径更新猫鼬

时间:2018-10-16 12:31:49

标签: javascript node.js mongodb mongoose

我的模型如下:

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

这是我的代码:

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

问题是,如果我尝试执行此操作^^^^^我的节点对我大喊:

  

/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:意外的模板字符串

但是,如果我尝试这样做:

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

我的IDE告诉我实际上在查询中未使用path变量。我该如何解决?我真的需要ID是动态的。

2 个答案:

答案 0 :(得分:1)

尝试以下查询

  

在mongo GUI上测试。

const mongoose = require('mongoose');


db.getCollection('content')
  .update({
    'attendants.employers.id': mongoose.Types.ObjectId((req.params._id)
    }, {
    $inc: { "attendants.employers.$.boothVisits": 1 }
  })

答案 1 :(得分:0)

尝试吗?:

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