javascript - 在 Mongoose 中用这个和 $in 获取 "Maximum call stack size exceeded"

标签 javascript mongoose

当我尝试在 pre 删除 Mongoose 5 中的中间件。

如果我将 .where.inthis 一起使用,我不会收到此错误。

const UserSchema = new Schema({
    name: String,
    blogPosts: [{
        type: Schema.Types.ObjectId,
        ref: 'blogPost'
    }],
});

UserSchema.pre('remove', async function() {
    const BlogPost = mongoose.model('blogPost');

    //This line throws the RangeError
    await BlogPost.deleteMany({ _id: { $in: this.blogPosts } });

    //This one works
    await BlogPost.deleteMany().where('_id').in(this.blogPosts);
});

我这里做错了什么?

编辑: 使用 this 时模型文件内部出现问题,如果我尝试 console.log this 我会收到此错误,或者,在这种情况下, this.blogPosts$in 一起使用时。

编辑 2: 在调试源代码时,我找到了出现此错误的原因。

这是因为我的 BlogPost 架构也有对 User 的引用。它加载 User,然后 User 加载 BlogPost,然后 BlogPost 加载 User,依此类推,直到超过最大调用堆栈。

我只是不知道为什么它只在某些情况下发生,比如第一个 deleteMany 调用。

最佳答案

问题出在我的 app.js 文件中。

我创建了一个示例函数来执行每个 crud 操作。

它正在做这样的事情:

const user = new User({...
const blogPost = new BlogPost({...

//saving, updating and retrieving...

user.remove();

最后一行导致错误,所以我将 user.remove() 替换为以下代码:

const doc = User.findOne({});

doc.remove();

现在一切正常。

奇怪的是,调用 remove() 使用与 new 模型相同的引用导致了这个问题。

关于javascript - 在 Mongoose 中用这个和 $in 获取 "Maximum call stack size exceeded",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54319212/

相关文章:

javascript - 如何修复我用 javascript 制作的 slider

javascript - 不能使用嵌套 anchor

javascript - Uncaught ReferenceError : $ is not defined when loading bootstrap date time picker in mvc

mongodb - 处理 Mongoose 中的模式更改

node.js - mongodb - 使用 $geoNear 在使用 maxDistance 时给出 "geo near accepts just one argument when querying for a GeoJSON point"

javascript - 如何使用输入上传图像,然后使用 img 标签渲染它的 View ?

MongoDB/ Mongoose : many to many relationship

node.js - 为什么 Node.js 需要 Mongoose 或 Mongojs?

javascript - Node js mongodb 中的异步/等待处理错误

javascript - SAPUI5 : How to find the item from sap. m.list 如果我只有该对象?