2017-04-24 71 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,這應該工作,但爲什麼你會想要這樣做? –