【发布时间】:2021-05-11 00:47:07
【问题描述】:
感谢您抽出宝贵时间阅读本文。
我正在使用 Node.js/Mongoose/MongoDB 制作博客应用程序。目前,我正在努力弄清楚如何同时更新 2 个集合。 我的 userSchema 有 postSchema 数组,我想在更新文档时同时更新用户和帖子集合。
我的代码在这里:
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: String
});
const Post = mongoose.model('Post', postSchema);
const userSchema = new mongoose.Schema({
username: String,
password: String,
displayName: String,
provider: String,
posts: [postSchema],
drafts: [postSchema]
});
const User = mongoose.model('User', userSchema);
app.post('/edit/:title', function (req, res) {
Post.findOneAndUpdate({ title: req.params.title }, {
title: req.body.title,
content: req.body.content
}, function (error, post) {
if (error) {
console.log(error);
} else {
res.redirect('/dashboard');
}
});
});
目前,我的代码只更新帖子集合,用户集合中的 postSchema 数组保持不变。谁能帮我解决这个问题?
【问题讨论】:
-
您是否有意保留帖子数据的两份副本而不是对
Post的引用? -
您是指用户内部的“帖子”和“草稿”吗?我将它们用于不同的目的......请忽略那部分。我只想更新用户集合中的 postSchemas。
-
有一个 Posts 集合,那么 Posts 也嵌入到 User 模式中。它似乎在重复数据
标签: javascript node.js mongodb mongoose