我有两个不同的模式User和Article一个用户可以发布多篇文章,其关系是一对多。
const mongoose = require("mongoose");
const userSchema = mongoose.Schema(
{
username: {
type: String,
required: [true, "Please add the username"],
}
articles: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Article'
}]
);
module.exports = mongoose.model("User", userSchema);
Article Schema是:
const mongoose = require("mongoose");
const articleSchema = mongoose.Schema(
{
postTitle: {
type: String,
required: [true, "Please add Post Title"],
},
publisher: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
);
module.exports = mongoose.model("Article", articleSchema);
这是我的创建文章控制器:
const createArticle = asyncHandler( async(req, res, next) =>
{
const { postTitle } = req.body;
const currentUser = req.user;
const article = await Article.create(
{
postTitle,
publisher: currentUser.id
}
)
res.status(201).json(article);
}
);
我希望当我创建一篇文章时,发布者会得到用户对象,这确实发生了,但我所期望的是用户对象字段文章也应该填充该文章ID为什么没有发生?因为我已经在他们schehmas中建立了关系
2条答案
按热度按时间yh2wf1be1#
通过更新/创建您的文章文档,它只会将文章Map到用户,您必须通过文章引用(文章ID)更新用户,以将用户Map到文章。
你可以这样做:1.保存(创建)文章后,您将获得文章文档作为回报。2.使用该文章文档ID(article._id)更新用户中的文章字段。
我认为这是唯一的方法,你可以Map用户的文章,反之亦然。
wqsoz72f2#
到目前为止我找到的解决办法是这样做
将文章的
_id
添加到用户的articles数组中: