枝,
我有一个下面给出的格式的模式。
var parentSchema = mongoose.Schema({
id:Schema.Types.ObjectId,
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true },
country_id : Schema.Types.ObjectId,
children: [
{
id: Schema.Types.ObjectId,
child_name: String,
standard_id: Schema.Types.ObjectId,
total_gold: { type: Number},
total_diamonds:{ type: Number },
total_hearts: { type: Number},
subjects: [
{
subject_name :String,
grade_name : String,
games: [ { id: String,
name: String
}
]
}
]
}
]
});
module.exports = mongoose.model('Parent', parentSchema);
parent是模型,children是一个对象数组,内部包含一个名为subject的数组。主题还包含一个名为games的数组。
如何使用该模型将数据推送到主题和游戏阵列? 这就是我在做的事情。
Parent.findOne({'username' : req.body.username}, function(err, parent) {
if (err)
res.json(err);
// if the user is found, then log them in
if (parent) {
res.json(parent);
}
else
{
var parent = new Parent();
parent.username = req.body.username;
parent.password = req.body.password;
parent.children.push({
child_name: req.body.childname,
total_gold:0,
total_diamonds:0,
total_hearts: 0
});
}
如何将数据推送到主题数组和游戏数组?
答案 0 :(得分:0)
要回答您的问题,您应该制作不同的模式并添加来自不同模型的对象。在父模式中,您只需将objectids保存为对子项的引用,如下所示:
var childSchema = mongoose.Schema({
child_name: String,
standard_id: mongoose.Schema.Types.ObjectId,
total_gold: { type: Number},
total_diamonds:{ type: Number },
total_hearts: { type: Number},
subjects: [
{
subject_name :String,
grade_name : String,
games: [
{
id: String,
name: String
}
]
}
]
});
mongoose.model('Child', childSchema);
var parentSchema = mongoose.Schema({
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true },
country_id : mongoose.Schema.Types.ObjectId,
children: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Child'
}
]
});
mongoose.model('Parent', parentSchema);
稍后您可以填充,有关此检查的更多信息http://mongoosejs.com/docs/populate.html
根据请求,示例正文为:
{
child_name: 'name',
total_gold: 23,
total_diamonds: 14,
total_hearts: 21,
subjects: [
{
subject_name: 'this is an example name',
grade_name: 'this is an example grade name',
games: [
{
id: 'id1',
name: 'name1'
},
{
id: 'id2',
name: 'name2'
}
]
}
]
}
添加新项目:
Child.create(req.body, function (err, doc) {
if (err) {
// Do something with the error
}
else {
// send the response
}
});