mongodb 有没有办法在Express Js和Mongoose中分别存储一对一、一对多或多对多的关系(Ids)?

bsxbgnwa  于 12个月前  发布在  Go
关注(0)|答案(2)|浏览(72)

我有两个不同的模式UserArticle一个用户可以发布多篇文章,其关系是一对多。

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中建立了关系

yh2wf1be

yh2wf1be1#

通过更新/创建您的文章文档,它只会将文章Map到用户,您必须通过文章引用(文章ID)更新用户,以将用户Map到文章。
你可以这样做:1.保存(创建)文章后,您将获得文章文档作为回报。2.使用该文章文档ID(article._id)更新用户中的文章字段。
我认为这是唯一的方法,你可以Map用户的文章,反之亦然。

wqsoz72f

wqsoz72f2#

到目前为止我找到的解决办法是这样做
将文章的_id添加到用户的articles数组中:

await User.findByIdAndUpdate(currentUser.id, { $push: { articles: article._id }, });

相关问题