0

I'm attempting to get a better grasp on Express.js, and am trying to create a simple blogging site.

My user model is simple: Username, Display Name, and an array of posts.

const userSchema = new Schema({
    username: {
        type: String,
        required: true, 
        unique: true, 
        trim: true, 
        minlength: 3
    },
    displayname: {
        type: String,
        required: true,
        minlength: 1
    },
    posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
}, {
    timestamps: true,
});

The same goes for my Post model: content and author.

const postSchema = new Schema({
    body: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 140
    },
    author: { type: Schema.Types.ObjectId, ref: 'User', required: true }
});

I've successfully created a new user and post:

[
  {
    "posts": [],
    "_id": "5d32c9474e28f66c08119198",
    "username": "Prince",
    "displayname": "The Artist",
    "createdAt": "2019-07-20T07:56:55.405Z",
    "updatedAt": "2019-07-20T07:56:55.405Z",
    "__v": 0
  }
]

[
  {
    "_id": "5d34af1ecae7e41a40b46b5a",
    "body": "This is my first post.",
    "author": "5d32c9474e28f66c08119198",
    "__v": 0
  }
]

Here's my routes for creating a user and post

//Create a user
router.route('/create').post((req, res) => {
    const username = req.body.username;
    const displayname = req.body.displayname;

    const newUser = new User({
        username, 
        displayname
    });

    newUser.save()
        .then(() => res.json('New user created!'))
        .catch(err => res.status(400).json(`Error: ${err}`));
});
//Create A Post
router.route('/create').post((req, res) => {
    const body = req.body.body;
    const author = req.body.author;
    const newPost = new Post({
        body,
        author
    });

    newPost.save()
        .then(() => res.json('Created new post!'))
        .catch(err => res.status(400).json(`Error: ${err}`));
});

And my method to get all posts by a user:

//Get all posts by user
router.route('/posts/:id').get((req, res) => {
    User.findById(req.params.id)
        .populate('posts')
        .exec((err, user) => {
            if(err) {
                res.status(400).json(`Error: ${err}`);
            } else {
                res.json(user.posts);
            }
        });
});

Whenever I look at the response from /users/posts/:id, the array is empty, but I would expect it to be filled with the post made by the user with the ID I supply? Am I misunderstanding how populate works?

1 Answer 1

2

You need to add the posts id to the users post list in order for mongoose's populate to work properly.

router.post('/create' async (req, res) => {
    const body = req.body.body;
    const author = req.body.author;
    const newPost = new Post({
        body,
        author
    });
    try {
        const user = await User.findById(author);
        const post = await newPost.save()
        user.posts = user.posts.concat(post._id)
        await user.save()
        return res.json(post.toJSON())
    } catch (e) {
        return res.status(400).json(`Error: ${e}`));
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

I just ran into this issue and can confirm it works. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.