Home > Software design >  How to save a subdocument (embedded) with a reference in mongoose?
How to save a subdocument (embedded) with a reference in mongoose?

Time:04-19

I have this 2 mongoose schemas, the first is embedded in the second

const mongoose = require("mongoose");

const CommentSchema = mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    text: {
        type: String,
        minLength: 3,
        maxlength: 500,
        required: true
    },
}, {timestamps: true} );

const PictureSchema = mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    title: {
        type: String,
        minLength: 3,
        maxlength: 80,
        required: true
    },
    comments: [CommentSchema]
}, {timestamps: true} );

module.exports = mongoose.models.Picture || mongoose.model('Picture', PictureSchema);

Both schemas are in the same file. Note that both documents refer to another Schema called User. I am getting an error when saving:

const comment = new Comment({
    user: user,
    text: description
});

const picture = new Picture({
                user: user,
                title: title
});

picture.comments.push(comment);
await picture.save();

user is a user object from the other schema, I am confident it is good as previous to add the comments array it was working.

the error I am getting says ReferenceError: Comment is not defined

It looks to me that because I am including Picture like this

const Picture = require('../model/Picture');

it can't find Comment, but I tried putting them in 2 separated files and still not working.

What am I doing wrong?

CodePudding user response:

It seems to me you only have problem with module exports. To make Comment accessible from external file, you need to export it.

In the end of schema definition file use:

module.exports.Picture = mongoose.models.Picture || mongoose.model('Picture', PictureSchema);
module.exports.Comment = mongoose.models.Comment || mongoose.model('Comment', CommentSchema);

In the file where you use models use:

const { Picture, Comment } = require('../model/Picture');
  • Related