MongoDB栈溢出异常:首次关联Outlet创建Remote时进程崩溃
Hey there, let's break down why you're hitting this stack overflow issue only on AWS when creating the first Remote for an Outlet, and how to fix it.
Root Cause
The problem stems from a circular reference between your Remote and Outlet documents in memory. Here's what's happening:
- You retrieve the full
Outletdocument usingOutlet.findById. - You assign the entire
outletdocument toremoteData.outletinstead of just its ObjectId. - After creating the
Remote, you push the fullremotedocument intooutlet.remotes. - Now you have a loop: the
Remotereferences the fullOutlet(which contains theRemote), and theOutletreferences the fullRemote(which contains theOutlet). - When sending the response with
res.json(remote), Mongoose's internal cloning/serialization process tries to recursively copy this circular structure, leading to infinite recursion and a stack overflow.
This only happens the first time because after the first Remote is added, subsequent creates don't trigger the same circular reference chain in the in-memory documents (or your local environment handles it more gracefully due to subtle version differences).
Solution
The fix is simple: use ObjectIds instead of full documents when setting up references. This breaks the circular loop and stops the infinite recursion.
Modified Backend Create Method
Here's how to adjust your create function:
create(req: any, res: any, next: any) { Outlet.findById(req.body.oId, function (err: any, outlet: any) { if (err) { return next(err); } var remoteData = req.body; delete remoteData.oId; // Use the ObjectId instead of the full outlet document remoteData.outlet = outlet._id; Remote.create(remoteData, function (err: any, remote: any) { if (err) { return next(err); } // Push the Remote's ObjectId to the outlet's remotes array (explicit and safe) outlet.remotes.push(remote._id); outlet.save(function (err: any) { res.json({ type: true, data: remote, }); }); }); }); }
Key Changes:
remoteData.outlet = outlet._id: Ensures the Remote only stores a reference to the Outlet's ID, not the full document.outlet.remotes.push(remote._id): Explicitly pushes the Remote's ID to the Outlet's remotes array (Mongoose would handle converting the full document to an ID automatically, but this is safer and clearer).
Why This Works
By using ObjectIds instead of full documents for references, you eliminate the circular reference in memory. When Mongoose serializes the Remote document to JSON for the response, it only includes the Outlet's ID, not the full Outlet object—so there's no loop to cause infinite recursion.
This should resolve the stack overflow error on AWS while maintaining all your existing functionality.
内容的提问来源于stack exchange,提问作者Elia Weiss

