mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Re-saving an array with references to another collection fails

Open AdrianSchneider opened this issue 9 years ago • 3 comments

Bug: If you re-save an array of objects which are pulled from another collection, it fails to save. In hindsight, we probably shouldn't do this, but this turned into a fairly deep rabbit hole of pain since it's allowed and has been in production for a few years.

This behaviour was introduced in 4.11.7 (works in 4.11.6 and below) and is still present in master. Fails on both node 4.4.7 and 6.9.4. Probably relevant:

fix(document): ensure overwriting a doc array cleans out individual docs #5523

it('Cannot re-nest subdocs from another collection', function(done) {
  var MainSchema = new Schema({
    name: { type: String },
    children: [{
      _id: { type: mongoose.Schema.ObjectId },
      name: { type: String }
    }]
  });
  var RelatedSchema = new Schema({ name: { type: String } });
  var Model = db.model('tmain', MainSchema);
  var RelatedModel = db.model('trelated', RelatedSchema);

  var relation = new RelatedModel({ name: 'what' });
  relation.save(function(err) {
    if (err) return done(err);

    var doc = new Model({ name: 'test1', children: [relation] });
    doc.save(function(err) {
      if (err) return done(err);
      doc.children = [relation];
      doc.save(done); // boom
    });
  });
});
MongoError: cannot use the part (children of children.-1._id) to traverse the element ({children: [ { _id: ObjectId('59b2e03a5c80674c59d6ad02'), name: "what" } ]})

The current delta it's trying to apply, is: (from model.$__delta())

[
    {
        "_id": "59b2e201eebe2056c9b3f3bb",
        "__v": 0
    },
    {
        "$set": {
            "children.-1._id": [
                null
            ],
            "children.-1.name": [
                null
            ]
        },
        "$inc": {
            "__v": 1
        }
    }
]

which looks like complete madness >.<

AdrianSchneider avatar Sep 08 '17 18:09 AdrianSchneider

@AdrianSchneider , hi If you still need this behavior with re-updating the document. Could you don't use save and just replace it with code:

// old 
doc.children = [relation];
doc.save(done); // boom
// new
Model.findByIdAndUpdate(doc.id, {$set: {children : [relation]}}, {new: true}, done);

koliaVasyliv avatar Sep 11 '17 18:09 koliaVasyliv

Thanks for the detailed bug report, will try to repro and get back to you asap.

vkarpov15 avatar Sep 20 '17 00:09 vkarpov15

yeah you actually dont even need to specify the _id for the related schema bc mongoose will automatically do that, but the bug is still definitely present:

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const { Schema } = mongoose;

mongoose.connect(`mongodb://localhost:27017/gh-5632`, { useMongoClient: true });

var MainSchema = new Schema({
  name: { type: String },
  children: [{
    // rel: { type: mongoose.Schema.ObjectId },
    name: { type: String }
  }]
});
var RelatedSchema = new Schema({ name: { type: String } });
var Model = mongoose.model('tmain', MainSchema);
var RelatedModel = mongoose.model('trelated', RelatedSchema);

var relation = new RelatedModel({ name: 'what' });
relation.save(function(err) {
  if (err) {
    console.error(err);
    return;
  }

  var doc = new Model({ name: 'test1', children: [relation] });
  doc.save(function(err) {
    if (err) {
      console.error(err);
      return;
    }
    doc.children = [relation];
    doc.save((err2) => {
      if (err2) {
        console.error(err2);
        return;
      }
      console.log('done');
    }); // boom
  });
});

sobafuchs avatar Sep 21 '17 03:09 sobafuchs