Mongoose - RangeError: Maximum Call Stack Size Exceeded

后端 未结 7 2261
遇见更好的自我
遇见更好的自我 2020-12-08 14:38

I am trying to bulk insert documents into MongoDB (so bypassing Mongoose and using the native driver instead as Mongoose doesn\'t support bulk insert of an array of document

7条回答
  •  盖世英雄少女心
    2020-12-08 14:56

    Confirmed, but not a bug. Model.collection.insert() bypasses Mongoose and so you're telling the node driver to insert an object that contains mongoose internals like $__, etc. The stack overflow is probably because bson is trying to compute the size of an object that references itself indirectly.

    Long story short, use Document.toObject(), that's what its for: http://mongoosejs.com/docs/api.html#document_Document-toObject

    Response.find({}).exec(function(err, responses) {
      if (err) { 
        return callback(err); 
      }
    
      if (true) {
        var toInsert = [];
        responses.forEach(function(response) {
          console.log("Filling response: " + response._id);
          response.answers = [];
          [{ name: 'test' }].forEach(function(ans) {
            response.answers.push(ans);
          });
          toInsert.push(response.toObject());
        });
        Response.collection.insert(toInsert, function(err, responsesResult) {
          console.log(err);
        });
      } else {
          callback();
        }
    });
    

    Also, the code you specified won't work even if you fix the stack overflow. Since you're trying to insert() docs that are already in the database, all the inserts will fail because of _id conflicts. You'd really be much better off just using a stream() to read the results one at a time and then save() them back into the db.

提交回复
热议问题