mongo-mock icon indicating copy to clipboard operation
mongo-mock copied to clipboard

Updating a sub-document with ObjectId drops ObjectId content

Open LinusU opened this issue 4 years ago • 2 comments

The following code:

const productStateCollection = connected_db.collection('ProductState')
const productCollection = connected_db.collection('Product')

let product = (await productCollection.insert({
  name: 'Test'
})).ops[0]

let state = (await productStateCollection.insert({
  price: 4900
})).ops[0]

product = (await productCollection.findOneAndUpdate(
  { _id: product._id },
  { $set: { currentState: state } },
  { returnOriginal: false }
)).value

console.error(product)

Results in this printout:

{
  name: 'Test',
  _id: ObjectID(603cbb3222f6501e8bc31bd9),
  currentState: { price: 4900, _id: ObjectID(undefined) }
}

Note that currentState._id is ObjectID(undefined)

LinusU avatar Mar 01 '21 10:03 LinusU

I've tracked down the problem to somewhere inside the modifyjs dependency:

  console.error('original', original)
  console.error('updates', updates)
  var updated = modifyjs(original, updates);
  console.error('updated', updated)
original { name: 'Test', _id: ObjectID(603cbd6635df4f1f51b83992) }
updates {
  '$set': {
    currentState: { price: 4900, _id: ObjectID(603cbd6635df4f1f51b83993) }
  }
}
updated {
  name: 'Test',
  _id: ObjectID(undefined),
  currentState: { price: 4900, _id: ObjectID(undefined) }
}

LinusU avatar Mar 01 '21 10:03 LinusU

Okay, the problem is that bson-objectid ObjectId loses their internal data when they are cloned. This doesn't seem to be a problem with ObjectId from the official bson package.

LinusU avatar Mar 01 '21 10:03 LinusU