Home > OS >  Remove object from nested array in MongoDB using NodeJS
Remove object from nested array in MongoDB using NodeJS

Time:06-10

I can see that this question should have been answered here, but the code simply doesn't work for me (I have tried multiple, similar variations).

Here is my data:

[{
  "_id": {
    "$oid": "628cadf43a2fd997be8ce242"
  },
  "dcm": 2,
  "status": true,
  "comments": [
    {
      "id": 289733,
      "dcm": 2,
      "status": true,
      "clock": "158",
      "user": "Nathan Field",
      "dept": "IT",
      "department": [],
      "dueback": "",
      "comment": "test 1"
    },
    {
      "id": 289733,
      "dcm": 2,
      "status": true,
      "clock": "158",
      "user": "Nathan Field",
      "dept": "IT",
      "department": [],
      "dueback": "",
      "comment": "test 2"
    }
  ],
  "department": [],
  "dueback": ""
}]

And here is my code

const deleteResult = await db.collection('status').updateOne(
            { "dcm": comments.dcm },
            { $pull: { "comments": { "id": comments.id } } },
            { upsert: false },
            { multi: true }
        );

Absolutely nothing happens...

CodePudding user response:

So the issue ended up being something to do with running multiple update operations within one function. I have a database connection function like this:

const withDB = async (operations, res) => {
    try {
        const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
        const db = client.db('collection');
        await operations(db);
        client.close();
    } catch (error) {
        res.status(500).json({ message: 'Error connecting to db', error });
    }
}

And then I call this by using:

withDB(async (db) => {
    await db.collection('status').updateMany(
        { "dcm": comments.dcm },
        { $pull: { "comments": { "id": comments.id } } }, 
        { multi: true }
    );
});

The issue occurred it would seem because I had two of these update operations within one withDB function. I have multiple operations in other instances (update item, then fetch collection), but for some reason this caused an issue.

I created a separate call to the withDB function to perform the '$pull' (delete) request, and then updated the array with the new comments.

To check that there was nothing wrong with my actual query, I used Studio3T's IntelliShell feature. If I'd done that sooner I would saved myself a lot of time!

CodePudding user response:

You can try this.

{ $pull: { "comments": { "id": ObjectId(comments.id) } } },

I hope it will fix the issue.

  • Related