I'm looking to create a post using two mongoose models that are referencing each other. How can I do this effectively?

My goal is to create a Post with the author being the user who created it and have the Post added to the array of posts in the user model that references "Post". Despite searching and watching tutorials, I'm still struggling to understand how to achieve this. I've come across the "populate" method, but I specifically want to create a new post with the author as the user's name and have it added to the user's posts array. How should I approach this?

Here is the post creation controller:

exports.postCreatePost = (req, res) => {

    const {
        title,
        description,
        context
    } = req.body;

    const post = new Post({
        title,
        description,
        context,
        author: 
    })

}

And here is the model.js:

const mongoose = require("mongoose"),
        Schema = mongoose.Schema,
        bcrypt = require("bcryptjs");

        const postSchema = new Schema({
            title: String,
            description: String,
            context: String,
            author: {
                type: Schema.Types.ObjectId,
                ref: "User"
            }
        });

        const userSchema = new Schema({
            name: {
                type: String,
                required: true
            },

            email: {
                type: String,
                required: true,
            },

            password: {
                type: String,
                required: true
            },

            posts: [{
                type: Schema.Types.ObjectId,
                ref: "Post"
            }]
        });

        userSchema.pre("save", async function save(next) {
            const user = this;
            if (!user.isModified("password")) return next();
            const hashedPassword = await bcrypt.hash(user.password, 10);
            user.password = hashedPassword;
            next();
        });

const Post = mongoose.model("Post", postSchema);
const User = mongoose.model("User", userSchema);
const userId = new mongoose.Types.ObjectId();

Answer №1

To obtain the username/id from the client, you can either receive it from req.body or pass the user reference during authentication to be included in the request body.

For instance, if the client provides an id/username, you can implement it like this

const post = new Post({
    title,
    description,
    context,
    author: req.body.username or req.body.id
})

To perform a push operation, follow this approach

await findOneAndUpdate({_id: req.body.id}, {
        "$push":
        {
            "posts": post._id
        }
    })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to move a directive within a limited parent element?

Is there a way to limit the movement of an angular.js drag directive within the confines of its parent element? You can see the problem I'm facing in this jsbin: http://jsbin.com/maxife/3/edit?html,css,js,output ...

Tips on how to highlight a clicked list item:

I'm currently attempting to access the key={1} Element within my li. My goal is to set the activeItem in State in order to compare it with the clicked item later on. If they are equivalent, I want to apply an active class to that specific element. How ...

UI experiencing issues with selecting radio buttons

When trying to select a radio button, I am facing an issue where they are not appearing on the UI. Although the buttons can be clicked, triggering a function on click, the selected option is not displayed visually. <div data-ng-repeat="flagInfo in avai ...

JavaScript Datepicker Formatting

I need to modify the date format of a datepicker. Currently, it displays dates in MM/DD/YYYY format but I want them to be in DD-MM-YYYY format. <input id="single-date-picker" type="text" class="form-control"> Here's the JavaScript code: $("# ...

Troubleshooting Mobile App Errors with Rails API

My mobile application is connected to a Rails server. I am encountering an issue when attempting to edit an Item in the Rails database using a JSON request from my application. The first time I make the AJAX request, I receive an error message. {"readySta ...

Utilizing JavaScript to implement a single method across multiple objects

Recently, I encountered a problem while trying to use the prototype method to apply the same function or variable to multiple objects. Despite creating numerous objects in the following manner: var item = { a: { aa: "lalala", ab: 1, somethin ...

Concentrating on a Div Element in React

I'm trying to set up an onKeyPress event that will be triggered when a key is pressed while a 'Level' element is displayed. I know that the div needs to be focused for events to register, but I'm not sure how to do this with functional ...

Encountering difficulty in implementing two modals simultaneously on a single web page while utilizing the useDisclosure() hook in Ch

ChakraUI provides a custom hook called useDisclosure() which gives you access to isOpen, onClose , onOpen. const { isOpen, onOpen, onClose } = useDisclosure() You can use the onOpen function as an onClick handler for a button to open a modal. <Modal ...

When using selenium-python, every attempt to click a button consistently results in an error message

I've been trying to use Python-Selenium binding to click a button, but I haven't had any luck with various selectors so far. I'm currently using Chromedriver. Although I can select an element using elem = driver.find_element(by='xpath& ...

Tips for streamlining this code

Currently, I am in the process of creating a new train and updating the available seat information for the next 5 days on that train. However, the code I have written is quite repetitive. I am seeking advice on how to simplify and optimize this code. In o ...

JavaScript: The power of nested array manipulation

I'm having trouble extracting data from a parsed JSON array obtained from a shipping company. Specifically, I am attempting to retrieve the short_name of Cleveland, OH, but all my attempts to access this information have been unsuccessful. When I use: ...

Is there a way to horizontally center Material UI Switch and its icon props?

I'm using Material-UI to implement a Switch component on my project. This particular component allows for the addition of icons, however, I've encountered an issue with alignment when including them. Is there a way to horizontally center align b ...

What is the process for importing a submodule in webpack?

I've set up a React component in an npm package called 'share-sheet'. This component is managed by webpack with the following configuration: webpack.config.js ... output: { path: path.join(__dirname, '/dist'), filename: & ...

Is it possible for Vue data to be handled asynchronosly

Have you ever wondered? Is it possible for Vue's data function to be asynchronous? Imagine needing to fetch data from an API using a library like axios, which only offers async methods. How can this data be loaded into Vue's data function? Con ...

Could one potentially generate new static files in Nextjs without needing to rebuild the entire app?

After recently beginning to utilize NextJs' getStaticProps feature, I have found that the static files generated at build time are quite impressive. However, my content is not static and requires updates without having to rebuild the entire app each t ...

Executing asynchronous requests in Angular 6 API

I've come across an issue in my API file where I am unsure how to manage two async calls to execute the function in order. Can someone provide assistance on resolving this problem or suggest if using a promise could help solve it? Thank you in advanc ...

Trouble fetching the concealed field data within the MVC framework

Upon executing the code provided below on an ASP.NET web form, I noticed that the value of the hidden field customerDeviceIdReferenceCode appears in the page source. <div id="customerDeviceIdReferenceCode" style="display:none;"> <inpu ...

Unpacking Functions within Embedded Redux Reducer

My current challenge involves dispatching an action that has the following structure: { type: "TOGGLE_FARA", fara: true, id: "5d20d019cf42731c8f706db1" } The purpose of this action is to modify the "enabled" property within my "fara" state. The configura ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

What is the best way to retrieve all the values of a specific field from a store?

Is there a way to retrieve all the values of a specific field from a store without manually selecting each cell? In my grid, I am looking to extract all the values from a particular column directly from the store. Is this achievable without any manual sel ...