想在.push方法上将嵌入式结构的字段推送到嵌入式模型文档中。 http://mongoosejs.com/docs/2.7.x/docs/embedded-documents.html
虽然控制台出错了这个问题:SyntaxError: Unexpected token .
..用于在嵌入模型中嵌入嵌入时推送bar.this : req.body.this,
模型看起来像这样:
var OneModel = new Schema({
foo: String,
bar: {
this : String,
that : Number,
}
});
var TwoModel = new Schema({
foo: String,
bar: {
this : String,
that : Number,
},
modelone: [OneModel]
});
NodeJS API看起来像这样:
var ModelsOneTwo = require('./app/models/modelsonetwo');
router.route('/modeltwo/:modeltwo_id')
// update TwoModel with this _id
//(accessed at PUT http://localhost:4200/api/v1/modeltwo/:modeltwo_id)
.put(function(req, res) {
ModelsOneTwo.findById(req.params._id, function(err, modeltwo) {
if (err)
res.send(err);
// embedded document updating
// http://mongoosejs.com/docs/2.7.x/docs/embedded-documents.html
modeltwo.modelone.push({
foo : req.body.foo,
bar.this : req.body.this,
bar.that : req.body.that
});
// save the modeltwo, and check for errors
modeltwo.save(function(err) {
if (err)
res.send(err);
res.json({ message: req.params.modeltwo_id + ' ' + req.body.foo });
});
});
});
答案 0 :(得分:1)
要在模型中设置bar
的属性,您必须为其创建额外的Object
:
modeltwo.modelone.push({
foo : req.body.foo,
bar : {
this : req.body.this,
that : req.body.that
}
});
这类似于在架构中定义的方式:
var OneModel = new Schema({
foo: String,
bar: {
this : String,
that : Number,
}
});