我正在搞一个项目 - 跟踪我孩子的奖励 - 学习 Node 和 MongoDB/Mongoose 并遇到一个问题(这可能与试图掌握具有 SQL 数据库背景的 NoSQL 有关)。
我有两个架构(适用):Child 和 RewardDeposit。
孩子
models.mongoose.Child = mongoose.model('Child', new mongoose.Schema({
firstname: {
type: String,
required: true,
},
lastname: {
type: String,
required: true,
},
nickname: String,
datecreated: {
type: Date,
default: () => Date.now(),
immutable: true,
},
datemodified: Date,
deposits: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'RewardDeposit'
}
]
}));
奖励存款
models.mongoose.RewardDeposit = mongoose.model('RewardDeposit', new mongoose.Schema({
for: String,
qty: Number,
datecreated: {
type: Date,
default: () => Date.now(),
immutable: true,
},
datemodified: Date,
child: {type: mongoose.Types.ObjectId, ref: "Child"}
}));
我运行测试来创建一个 Child,然后创建一个与该 child 相关的 RewardDeposit
var cid = "";
const c = new models.mongoose.Child;
c.firstname = "XXXXX";
c.lastname = "XXXXXX";
c.nickname = "XXXXXXX";
c.save()
.then((c) => {
cid = c._id;
const d = new models.mongoose.RewardDeposit;
d.for = "YYYY";
d.qty = 10;
d.child = c;
d.save()
})
无论我以哪种方式编写填充/填充命令,子文档中的存款数组始终为空
models.mongoose.Child.findById(cid).populate('deposits');
我必须将奖励存款作为子文件吗?相关的顶级文档可以不填充吗?我的架构是否做错了?
子对象
{
"_id": "6707fd5f98df9d7355b35580",
"deposits": [],
"datecreated": "2024-10-10T16:14:23.719Z",
"firstname": "XXXXX",
"lastname": "XXXXXX",
"nickname": "XXXXXXX",
"__v": 0
}
奖励对象
{
"_id": "6707fd6098df9d7355b35583",
"datecreated": "2024-10-10T16:14:24.630Z",
"for": "YYYY",
"qty": 10,
"child": "6707fd5f98df9d7355b35580",
"__v": 0
}
您创建了新的
RewardDeposit
和 Child
,但未使用 Child
的 ID 更新 RewardDiposit
。我认为这就是为什么 deposits
上的 Child object
为空,但你有 reward object
因为你 .save()
它却忘了更新 Child
。
我花了一段时间来阅读你的代码,因为我还没有见过这样用 Nodejs 编写的代码。
但我认为我编写的这段代码会起作用,或者给你一些关于它如何工作的想法。
var cid = "";
const c = new models.mongoose.Child;
c.firstname = "XXXXX";
c.lastname = "XXXXXX";
c.nickname = "XXXXXXX";
c.save() //you created the child with "depisits": []
.then((savedChild) => {
cid = savedChild._id;
const d = new models.mongoose.RewardDeposit;
d.for = "YYYY";
d.qty = 10;
d.child = savedChild; //you child filed is object so I would
//suggest you to write savedChild._id
return d.save(); //you created the reward deposit with child's id (line above this one)
})
//you forgot to update the child's deposits with the new deposit created above
.then((savedDeposit) => {
//now update the child's deposits array with the newly created RewardDeposit _id
return models.mongoose.Child.findByIdAndUpdate(
savedChild._id,
{ $push: { deposits: savedDeposit._id } },
{ new: true }
);
})
.then((updatedChild) => {
//check if the deposits in child is updated
console.log('Updated Child:', updatedChild);
})
.catch(err => {
console.error(err);
});
在这种情况下,我建议您使用
async/await
而不是 Promise
,因为代码很难阅读和理解。
希望这对您有帮助。