0

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();
    });

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

This is the correct way:

var user = request.body.user;
var new_friend = request.body.new_friend;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.