Khaled_ch
Khaled_ch

Reputation: 45

The dollar ($) prefixed field '$oid' in 'features.0._id.$oid' is not valid for storage

I have the following Mongo collection attached below. it is existing one not new collection created, I am trying to push new item in the features array, but I am not able to achieve that due to the following error: The dollar ($) prefixed field '$oid' in 'features.0._id.$oid' is not valid for storage. using this script:

db.getCollection("test").update({ _id: "RYB0001" },
{
  $push: {
    "features": {
      "_id": {
          "$oid": ObjectId(),
      },
      "featureItems": [],
      "typeId": "type3"
    }
   }
});

If it is a driver version issue, any workaround can I do to push the new item to the current collection? MongoDb version: 4.0.4 Mongo Collection screenshot

Upvotes: 4

Views: 5916

Answers (1)

Plancke
Plancke

Reputation: 1139

The $oid notation is part of MongoDB's Extended JSON. I assume the data in your database doesn't actually have that key-value pair and it was only represented that way after using something like JSON.stringify(obj)

> db.test.find({});
{ "_id" : "RYB0001", "features" : [ { "_id" : ObjectId("5e40d46a97abdef3faa0d5d9"), "featureItems" : [ ], "typeId" : "type3" } ] }
> JSON.stringify(db.test.find({})[0]);
{"_id":"RYB0001","features":[{"_id":{"$oid":"5e40d46a97abdef3faa0d5d9"},"featureItems":[],"typeId":"type3"}]}

You'll need to generate a new ObjectId using its constructor "_id": new ObjectId(), note the new keyword there, I think @Thilo may have missed that in their comment.

db.getCollection("test").update({ _id: "RYB0001" },
{
  $push: {
    "features": {
      "_id": new ObjectId(),
      "featureItems": [],
      "typeId": "type3"
    }
   }
});

Upvotes: 2

Related Questions