skip to Main Content

I have two Different Schemas User and Article
A user can publish many articles for which the relationship is One to Many
The scehmas are as follows

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 is:

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);

This is my create Article Controller:

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);
}
);

I am expecting when I create an article the publisher gets the user object which is indeed happening, but what I am expecting is the User Object field article should also be populated with that Article id
Why is this not happening? since I already made relation in their schehmas

2

Answers


  1. Chosen as BEST ANSWER

    The solution I found till now is by doing this

    `// Add the article's _id to the user's articles array

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


  2. By updating/creating your article doc it will only map article to user only,you have to update the user also by article refrence(article ID) to map user to article.

    here is how you can do it:
    1.After saving(creating) the article you will get the article doc in return.
    2.Use that article doc ID(article._id) to update article field in your user.

    I think this is the only way you can map user to article and vice-versa.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search