我正在尝试更新元素。
//模式
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'"
并且应用崩溃了
答案 0 :(得分: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架构this
上找到更多信息您可以找到有关Mongoose关系的更多信息here