express - 如何在猫鼬上链接文档
问题描述
我是新来表达发展,我正在尝试建立一个博客。我已经建立了两个模型,一个用于帖子,一个用于使用。在用户架构上,我有一个属性 posts 来在用户创建帖子时保存帖子。在控制器上,在我首先创建帖子之前,我从 req.params 获取用户的 ID,然后我通过 findbyid 函数检索用户并尝试将帖子保存在用户的帖子属性上,但没有成功。
const mongoose = require("mongoose");
UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
posts: [{type: mongoose.Schema.Types.ObjectId, ref: "Post"}]
})
module.exports = mongoose.model("User", UserSchema);
const Post = require("../model/post");
const User = require("../model/user");
module.exports = {
new: (req, res) => {
res.render("new_post");
},
post_new: (req, res) => {
const title = req.body.title;
const article = req.body.article;
const id = req.params.id;
const post = new Post({
title: title,
article: article,
})
User.findById(id)
.then(user => {
user.posts.push(post);
})
//post.created_by.push(id);
post.save()
.then(result => {
console.log("Post has created");
res.redirect("/");
});
}
};
解决方案
我看到一些问题。
您user
的架构不应包含posts
. 相反,您的post
架构应该有一个名为user
/的字段userId
来存储用户 ID。例子:
const PostSchema = new mongoose.Schema({
title: { type: String },
....,
userId: {type: mongoose.Schema.Types.ObjectId, ref: "User"}
});
现在你的post_new
功能应该是这样的。
post_new: async (req, res) => {
const title = req.body.title;
const article = req.body.article;
const id = req.params.id;
const post = await Post.create({
title: title,
article: article,
userId: id
});
console.log("Post has created");
res.redirect("/");
}
如果您想坚持自己的方式,那么create_new
功能应该是这样的。
post_new: async (req, res) => {
const title = req.body.title;
const article = req.body.article;
const id = req.params.id;
const post = new Post({
title: title,
article: article,
});
const {_id} = await post.save();
const user = await User.findById(id);
user.posts.push(_id);
await user.save();
console.log("Post has created");
res.redirect("/");
}
推荐阅读
- c# - 类型的 DbContext 不能被池化
- c++ - 当 C++ 函数不从右值引用参数“移动”时,这是合理的方法吗?
- rust - 使用 into_serde 反序列化字符串会使应用程序恐慌
- oracle - 为什么使用来自不同应用程序的相同查询和相同 ODBC 连接获取不同数量的记录?
- javascript - 如果包装在函数中,CryptoJS 不会解密
- javascript - Javascript 函数无法正常用于 HTML 选择
- angular - Angular 图表的 Kendo UI 获取选择?
- node.js - 如何在会话中访问令牌(Shopify 访问令牌)
- angular - Angular 9 - 不再支持 resultSelector
- .net - 控制器和索引视图 ID 和名称匹配。.net MVC