如何在 mongoose 中保存带有引用的子文档(嵌入)?

How to save a subdocument (embedded) with a reference in mongoose?

我有这 2 个猫鼬模式,第一个嵌入在第二个中

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

两个模式都在同一个文件中。请注意,这两个文档都引用了另一个名为 User 的架构。保存时出现错误:

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

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

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

user 是来自其他模式的用户对象,我相信添加它正在工作的评论数组与以前一样好。

我收到的错误是 ReferenceError: Comment is not defined

在我看来是因为我包含了这样的图片

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

找不到评论,但我尝试将它们放在 2 个单独的文件中,但仍然无法正常工作。

我做错了什么?

在我看来你只有模块导出有问题。要使 Comment 可从外部文件访问,您需要将其导出。

在模式定义文件的最后使用:

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

在您使用模型的文件中使用:

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