当我尝试创建两个包含彼此引用的文档时,超出了最大调用堆栈大小

时间:2023-01-12 19:40:52

Below are my Schemas for post and reply.(simplified version)

以下是我发布和回复的模式。(简化版)

const PostSchema = new Schema({
    title: {
        type: String,
        required: true,
    },
    replies:[{type:Schema.ObjectId, ref:"Reply"}]
});

const ReplySchema = new Schema({
    post: {
        type:Schema.ObjectId,
        ref:"Post"
    },
    message: {
        type: String,
        required: true,
        minlength: 1,
    }
});

When I try to create and save the two objects that have references to each other. I am getting the error: Maximum call stack size exceeded

当我尝试创建并保存两个彼此引用的对象时。我收到错误:超出最大调用堆栈大小

let post = new Post({
    'title':postData.title
});

let reply = new Reply({
    'post': post,
    'message':postData.message
});

post.replies.push(reply);

post.save(function(err, post){
    if(err) return next(err);
    reply.save(function(err,reply){
        if(err) return next(err);
        res.status(201).json({'success':1});
    });
});

Thanks in advance.

提前致谢。

1 个解决方案

#1


0  

Problem solved. I just saw a similar question on this site. And the problem is when we want to pass a document as a ref property of another document. We have to use doc._id, instead of the doc itself.

问题解决了。我刚刚在这个网站上看到了类似的问题。问题是当我们想要将文档作为另一个文档的ref属性传递时。我们必须使用doc._id,而不是doc本身。

So here, we should not pass post directly:

所以在这里,我们不应该直接传递帖子:

let reply = new Reply({
    'post': post,
    'message':postData.message
});

Need to change to:

需要改为:

let reply = new Reply({
    'post': post._id,
    'message':postData.message
});

#1


0  

Problem solved. I just saw a similar question on this site. And the problem is when we want to pass a document as a ref property of another document. We have to use doc._id, instead of the doc itself.

问题解决了。我刚刚在这个网站上看到了类似的问题。问题是当我们想要将文档作为另一个文档的ref属性传递时。我们必须使用doc._id,而不是doc本身。

So here, we should not pass post directly:

所以在这里,我们不应该直接传递帖子:

let reply = new Reply({
    'post': post,
    'message':postData.message
});

Need to change to:

需要改为:

let reply = new Reply({
    'post': post._id,
    'message':postData.message
});