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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.