gpt4 book ai didi

node.js - 使用 Mongoose 模式获取嵌套数组引用?

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:50 27 4
gpt4 key购买 nike

我有一个下面给出的格式的架构。

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,
});
}
});

如何将数据推送到主题数组和游戏数组中?

最佳答案

要回答您的问题,您应该创建不同的架构并添加来自不同模型的对象。在父模式中,您只保存 objectid 作为对子模式的引用,如下所示:

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
}
});

关于node.js - 使用 Mongoose 模式获取嵌套数组引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24359650/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com