2017-04-24 70 views
1

我试图更新元素。

//架构

var SurveySchema = new Schema({ 
    id: String, 
    form: [{ 
      sections: [ // each section's a page 
       { 
        name: String, 
        description: String, 
        input: { 
         _type: String, 
         contents: [ 
          { 
           _id: false, 
           "text": String, 
           "value": String 
          } 
         ] 
        } 
       } 
      ] 
     }] 
}); 

//我的Json

{ 
    "_id": "58fe27e0e340671c9859c995", 
    "__v": 0, 
    "form": [ 
    { 
     "_id": "58fe2b1de437791cd02b9a8c", 
     "sections": [ 
      { 
       "_id": "58fe2b1de437791cd02b9a8d", 
       "input": { 
        "_type": "radio" 
       } 
      } 
     ] 
    }, 
    { 
     "_id": "58fe2ca32470711c586d6b6e", 
     "sections": [] 
    } 
    ] 
} 

//更新

var save = function(req, res) { 
    var survey = {}; 
    survey.id = req.params.surveyId; // 58fe27e0e340671c9859c995 
    survey.form_id = req.params.formId; // 58fe2b1de437791cd02b9a8c 

    Survey.update(
     { _id: survey.id, // 58fe27e0e340671c9859c995 
      'form._id': survey.form_id // 58fe2b1de437791cd02b9a8c 
     }, 
     {'$set': { 
      'form.$.sections.$.input._type': 'checkbox' 
     }}, 
     {safe: true, upsert: true}, 
     function(err, model) { 
      if (err) 
       res.send(err); 
      res.json(model); 
     } 
    ); 
}; 

我想换一个新的价值input._type'checkbox'上的ID :_id: 58fe2b1de437791cd02b9a8c,但我不断收到此错误消息:"Too many positional (i.e. '$') elements found in path 'form.$.sections.$.input._type'"和ap p崩溃。

+0

这表示您正在做某件事您应该做的事。 [见文档](https://docs.mongodb.com/manual/reference/operator/update/positional/#nested-arrays) – styvane

+0

你能发布你的猫鼬纲要吗 –

+0

@ DanGreen-Leipciger架构已发布。如果你想给一些提示,可以自由地说。 –

回答

1

你应该为每个不同类型的元素,你有(部分,输入)不同的模式

这给一个镜头:

const surveySchema = new Schema({ 
    name: String, 
    sections: [ 
    { 
     type: Schema.Types.ObjectId, 
     ref: 'Section' 
    } 
    ] 
}); 

const sectionSchema = new Schema({ 
    name: String, 
    description: String, 
    contents: [ 
    { 
     type: Schema.Types.ObjectId, 
     ref: 'Input' 
    } 
    ] 
}); 

const inputSchema = new Schema({ 
    text: String, 
    value: String, 
    _type: String 
}); 

const Input = mongoose.model('Input', inputSchema); 
const Section = mongoose.model('Section', sectionSchema); 
const Survey = mongoose.model('Survey', surveySchema); 

然后更新它

Input.update({ _id: id }, { $set: { _type: 'checkbox' }}); 

您可以在Mongoose模式上找到更多信息here

您可以找到更多o n猫鼬关系here

+1

这不会起作用 – styvane

+0

修复它,谢谢@ s.s –

+0

@Jose,这应该工作,但为什么你会想要这样做? –