Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongooseJS: Having a hard time populating a list of comments

I have a schema called Post, and in the Schema, there is a comments attribute.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const PostSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: "users",
    },
    text: {
        type: String,
        required: true,
    },
    name: {
        type: String,
    },
    avatar: {
        type: String,
    },
    likes: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: "users",
            },
        },
    ],
    comments: [
        {
                type: Schema.Types.ObjectId,
                ref: "comments",
        },
    ],
    date: {
        type: Date,
        default: Date.now,
    },
});

module.exports = Post = mongoose.model("post", PostSchema);

Here is my Comments schema.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
    post: {
        type: Schema.Types.ObjectId,
        ref: "posts",
    },
    user: {
        type: Schema.Types.ObjectId,
        ref: "users",
    },
    text: {
        type: String,
        required: true,
    },
    name: {
        type: String,
    },
    avatar: {
        type: String,
    },
    likes: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: "users",
            },
        },
    ],
    replies: [
        {
                type: Schema.Types.ObjectId,
                ref: "comments",
        },
    ],
    date: {
        type: Date,
        default: Date.now,
    },
});
module.exports = Comment = mongoose.model("comment", CommentSchema);

When I print out the data accessed by a post, I get it like below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "_id": "630a82d564540e7196fe4887",
    "user": "6301a168783647db9f7a37c8",
    "text": "For the police I say ____ you punk, reading my rights and ____ it's all junk",
    "name": "e",
    "avatar": "//www.gravatar.com/avatar/8fd046f9f8f50ab2903fa9fd6c845134?s=200&r=pg&d=mm",
    "comments": [
        "630aa7c425ae8add2b275b53",
        "630a834959110e8e3305b471",
        "630a83200cd98eb07fb5f543"
    ],
    "likes": [],
    "date": "2022-08-27T20:47:17.888Z",
    "__v": 3
}

I have tried to populate the comments shown below but I’m getting an error:

router.post(
    "/commentOnPost/",
    [auth, check("text", "Text is required").not().isEmpty()],
    async (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        try {
            const user = await User.findById(req.user.id);
            const post = await Post.findById(req.body.post_id).populate('comments');
            let newComment = Comment({
                post: post.id,
                text: req.body.text,
                name: user.name,
                avatar: user.avatar,
                user: req.user.id,
            });
            await newComment.save();
            post.comments.unshift(newComment);
            await post.save();
            return res.json(await post);
        } catch (err) {
            errorLog(err);
            res.status(500).send("Server error");
        }
    }
);
Sat Aug 27 2022 19:27:22 GMT-0400 (Eastern Daylight Time),  -> MissingSchemaError: Schema hasn't been registered for model "comments".
Use mongoose.model(name, schema)

>Solution :

In your Comment schema, you named model as "comment". But in the Post schema, you referenced it as "comments".

Change your code in Post schema like this:

comments: [{ type: Schema.Types.ObjectId, ref: "comment" }],
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading