我正在使用ExpressJS和Mongoose。我正在尝试在3级数组上添加数据,但似乎无法映射。这是我的示例代码:
这是我的模型架构,其中我的集合包含 Object ,其中包含 Element数组,而在其下方包含 SubElement数组
"_id" : "5ab1218975819",
"objectName" : "sample",
"elements" : [
{
"_id" : "5abkj2348",
"elementName" : "some text here",
"subElements" : [
{
"This is where I put my desired data"
}
]
}
]
模型
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var subElementSchema= new Schema({
subElementName: {type: String, required: true, trim: true},
subElements: {type: [subElementSchema], default: []}
}, {
versionKey: false
});
var elementSchema= new Schema({
elementName: {type: String, required: true, trim: true},
subElements: {type: [subElementSchema], default: []}
}, {
versionKey: false
});
var objectSchema= new Schema({
project: {type: String, required: true, trim: true, lowercase: true},
projectName: {type: String, required: true, trim: true},
objectName: {type: String, required: true},
elements: {type: [elementSchema], default: []},
createdAt: {type: Date},
updatedAt: {type: Date}
}, {
versionKey: false,
collection: 'objects'
});
exports.SubElement= mongoose.model('SubElement', subElementSchema);
exports.Element= mongoose.model('Element', elementSchema);
exports.Object= mongoose.model('Object', objectSchema);
控制器
这是发生操作的地方,其中request.params包含 element 的ID,应在其中插入 subElement 。我尝试使用 object.elements.subElements.push ,但它不起作用。它返回TypeError错误:无法读取未定义的属性“ push”
exports.createSubElement= function (req, res) {
var payload = req.body;
return Endpoint.Object.findOne({ 'elements._id': req.params.elementId}, { 'elements.$': 1}, function (err, object) {
if (err)
return res.status(500).send({ message: 'An error occured\nMessage: ' + err });
if (!object)
return res.status(404).send({ message: 'Element not Found' });
else {
var subElement= new Endpoint.SubElement(payload);
object.elements.subElements.push(subElement);
object.save(function (err) {
if (err)
return res.status(500).send({ message: 'An error occured\nMessage: ' + err });
return res.status(201).send({ subElement });
})
}
})
}
任何帮助将不胜感激。谢谢!