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

时间:2017-10-10 00:18:45

标签: node.js mongoose

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

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

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

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

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

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

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

需要更改为:

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