1

I would like to add new field into json already have in mongoDB Cosmos like this

{
    "_id" : "6396cde306fd2d1088d584e4",
    "userName" : "user-20526"
}

Now I would like to add a others field like this bellow userName field:

{
  "_id" : "6396cde306fd2d1088d584e4",
  "userName" : "user-20526",
  "others": [
     {
        "address" : "city",
        "phone" : "12345676543"
     }
  ]
}

I user this function to do that thing, with updateDocument but it's not works for me:

const updateDocuments = async (value, condition, collectionName) => {
    const DATABASE_COLLECTION_NAME = collectionName;
    if (!db)
        throw Error('findDocuments::missing required params');
    const collection = await db.collection(DATABASE_COLLECTION_NAME);
    const filter = { condition };
    const filterJSON = JSON.parse("{" + filter.condition + "}");
    const options = { upsert: true };
    // get value (condition) and convert it to correct JSON format before call it in update variable
    const getValue = { value }
    const valueJSON = JSON.parse("{" + getValue.value + "}");
    const updateDoc = {
        $set: valueJSON
    };
    return await collection.updateOne(filterJSON, updateDoc, options);
}

The above function only works when we update one field that already have in data, the example I would like to update userName data, then that function is work, If I use that function to add new one then it's not, not add new one, how can I create more to add new field as what I expected before

anyone please help me

Jin
  • 1,259
  • 1
  • 12
  • 24
  • 1
    By right `$set` operator will add new field if the field found not existed. [Behavior](https://www.mongodb.com/docs/manual/reference/operator/update/set/#behavior). Do you get any error? Or the query is worked but not update correctly. While what is the value of `valueJSON`? – Yong Shun Jan 30 '23 at 07:46
  • I got this issue @YongShun, "Unexpected token o in json at position 1" – Jin Jan 30 '23 at 07:49
  • 1
    Your error message looks like it is not a correct JSON. Will be great if you can share out the whole value (`filterJSON`, `updateDoc`) that pass in `await collection.updateOne()` for debugging purpose. – Yong Shun Jan 30 '23 at 07:52

0 Answers0