PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How to append in an array mongoDB

 May 13, 2022     append, database, javascript, mongodb     No comments   

Issue

How can i append something in an array after i search a specific object, Database looks like this:

{
    "_id": {
        "$oid": "608a0f3628588a3daca019c6"
    },
    "username": "paul",
    "password": "cacavaca",
    "question": "q1",
    "answer": "cutu",
    "friends": [mir],
    "groups": []
}
{
    "_id": {
        "$oid": "608a0f4328588a3daca019c7"
    },
    "username": "mir",
    "password": "123456",
    "question": "q1",
    "answer": "cutu",
    "friends": [],
    "groups": []
}

I want to search the object by username: paul and append alex in the friends array, i have tried this but its not wokring:

MongoClient.connect(uri, function(err, db) {
        var dbc = db.db("chat");
        dbc.collection("accounts").find({username: { $eq: user}}).update( [
            {
              $push: {
                friends:alex
              }
            }

        ])
        db.close();
    });

Solution

I think instead of use .find() method, you should use updateOne() like this :

MongoClient.connect(uri, function(err, db) {
    var dbc = db.db("chat");
    dbc.collection("accounts").updateOne({username: {$eq: user}}, {
       $push: {
           friends: alex
        }
    });
    db.close();
});

Supposing user and alex are variables defined above.

Also, maybe you can only write {username: user} without $eq but it depends your code and logic.



Answered By - Jérôme
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing