williamkapke / mongo-mock

Let's pretend we have a real MongoDB
MIT License
240 stars 74 forks source link

Updating a sub-document with ObjectId drops ObjectId content #144

Open LinusU opened 3 years ago

LinusU commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

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.