在添加之前填充:RangeError:超出最大调用堆栈大小

时间:2017-02-28 19:43:41

标签: javascript node.js mongoose mongoose-schema mongoose-populate

我想实现像plunker这样的在线编辑器。我已经定义了以下数据结构:post(即项目)包含folders列表(表示帖子的不同版本),而folder只是一个列表files

var PostSchema = new mongoose.Schema({
  folders: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Folder' }]
  ...
});

var FolderSchema = new mongoose.Schema({
    files: [{ name: String, body: String, editorOption: Object }],
    post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }
})

我想使用以下请求添加文件夹/版本(通过编辑器上的save按钮)。请注意,由于帖子可以同时在不同的地方打开,我们必须在向其添加版本之前从数据库中获取帖子,然后我们返回最新的帖子到控制器。

o.addFolder = function (id, folder) {
    return $http.post('/posts/' + id + '/editor/folders', folder, {
        headers: { Authorization: 'Bearer ' + auth.getToken() }
    })
}

router.post('/posts/:post/editor/folders', auth, function (req, res, next) {
    req.post.populate('folders', function (err, post) {
        if (err) return next(err);
        var folder = new Folder(req.body);
        folder.post = post;
        folder.save(function (err, folder) {
            if (err) return next(err);
            console.log("3 folder: "); console.log(folder);
            console.log("4 post: "); console.log(post);
            post.folders.push(folder);
            console.log("5 folder: "); console.log(folder);
            console.log("6 post: "); console.log(post);
            post.save(function (err, post) {
                if (err) return next(err);
                res.json({ folder: folder, post: post })
            })
        })
    })
});

这是一个测试日志,它尝试将2个文件的文件夹添加到空帖子中:

3 folder: 
{ __v: 0,
  post: 
   { _id: 58b5e86d8e328f58f3e87ac2,
     __v: 0,
     folders: [] },
  _id: 58b5e86d8e328f58f3e87ac3,
  files: 
   [ { name: 'index.html',
       body: '<!DOCTYPE html>\n<body>\nindex.html\n</body>\n</html>',
       editorOption: [Object],
       _id: 58b5e86d8e328f58f3e87ac5 },
     { name: 'script.js',
       body: '',
       editorOption: [Object],
       _id: 58b5e86d8e328f58f3e87ac4 } ] }
4 post: 
{ _id: 58b5e86d8e328f58f3e87ac2,
  __v: 0,
  folders: [] }
5 folder: 
events.js:85
      throw er; // Unhandled 'error' event
            ^
RangeError: Maximum call stack size exceeded

有谁知道那里有什么问题?

1 个答案:

答案 0 :(得分:1)

以下代码完成了我想要的。显然,req.post.folders.push(folder)可以将folder推送到最新 post。我们最终会populate

router.post('/posts/:post/editor/folders', auth, function (req, res, next) {
    var folder = new Folder(req.body);
    folder.post = req.post;
    folder.save(function (err, folder) {
        if (err) return next(err);
        req.post.folders.push(folder);
        req.post.save(function (err, post) {
            if (err) return next(err);
            req.post.populate('folders', function (err, post) {
                if (err) return next(err);
                res.json(post);
            })
        })
    })
});