【发布时间】:2014-08-13 02:57:03
【问题描述】:
我有下面给出的格式的架构。
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 是一个对象数组,内部包含一个名为subjects 的数组。主题还包含一个名为 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,
});
}
});
如何将数据推送到主题数组和游戏数组中?
【问题讨论】:
-
不清楚您所说的“我如何访问”是什么意思。您需要在问题中解释的是您想要做什么。更新?获得某些物品?
-
我要向数组中添加数据?
-
哪个数组?有几种。如何在您的问题中添加一些代码,甚至是失败的代码,以显示您正在尝试做的事情。
-
您的编辑现在实际上使您的架构无效。正如我之前所说,您最好的方法是显示一些“损坏的代码”来解释您正在尝试做什么。请不要要求完整的 CRUD 教程。有很多示例供您搜索。
-
我建议你回顾一下你为嵌套模式编写代码的方式,并做一些更类似于:Mongoose/MongoDB 中嵌套模式的正确模式是什么?
标签: node.js mongodb mongoose mongodb-query