1

I am trying to update a specific field in a concrete JSON object inside an JSON array with mongoose. My MongoDB contains:

db.users.find({username:"xxx"})
{ "_id" : ObjectId("56cb877e73da764818ec5ded"),..., "githubtoken" : [ { "token" : "9e37axxx", "username" : "xxx", "_id" : ObjectId("572a7cfafe95dec51d9cbf2d") }, { "token" : "4529yyy", "username" : "yyy", "_id" : ObjectId("572a7d3cfe95dec51d9cbf2e") } ] }

And I want to get the JSON object that matches with "username" : "yyy"and "user._id" = "56cb877e73da764818ec5ded" and change its token to "token" : "4529zzz" with mongoose, like this:

{ "_id" : ObjectId("56cb877e73da764818ec5ded"),..., "githubtoken" : [ { "token" : "9e37axxx", "username" : "xxx", "_id" : ObjectId("572a7cfafe95dec51d9cbf2d") }, { "token" : "4529zzz", "username" : "yyy", "_id" : ObjectId("572a7d3cfe95dec51d9cbf2e") } ] }

The schema of db is:

var userSchema = new Schema({
    username  : { type: String, required: true },
    ...

    githubtoken: [ { username: {type: String, required: false },
        token: {type: String, required: false}  }]

});

And update method:

    userSchema.statics.updateuser = function updateuser (query, update, options) {
        var promise = new Hope.Promise();
        this.findAndUpdate(query, update, options,function(error, user) {
            if (error) {
                return promise.done(error, null);
            }else {
                return promise.done(null, user);
            }
        });
        return promise;
    };

And in my service with express.js:

query =  {$and: [{_id: userid}, {githubtoken: {username:username, token:oldToken}} ]};
        update = {$set : {githubtoken:{username:username, token:token}}};

    options = { new: true};


    User.updateuser(query,update,options).then(function (error,user){
        if(error){
            return promise.done(error,null);
        }else{

}});

But it doesn't work, because remove all array of githubtokens and push only the new githubtoken, like this:

{ "_id" : ObjectId("56cb877e73da764818ec5ded"),..., "githubtoken" : { "token" : "4529zzz", "username" : "yyy", "_id" : ObjectId("572a7d3cfe95dec51d9cbf2e") }  }

Any idea? Thank you very much :D

Izaskun Peña
  • 177
  • 2
  • 4
  • 14

3 Answers3

0

Try changing the query like this:

var query = {
    {
        _id: new ObjectId(userid),
        'githubtoken.username': username,
        'githubtoken.token': oldToken
    }
};

And update like this:

var update = {
    $set: {
        'githubtoken.$.username': username,
        'githubtoken.$.token': token
    }
};
Radoslav Stoyanov
  • 1,460
  • 5
  • 27
  • 40
  • Mongoose return me error: The positional operator did not find the match needed from the query.Unexpanded update: githubtoken.$.token. – Izaskun Peña May 05 '16 at 14:28
  • It seems that for some of the userId, username and oldToken parameters in the query there is not a match. That makes the update to fail. If you set the `upsert` parameter to `true` then if there is not a match a new document will be created. – Radoslav Stoyanov May 05 '16 at 14:34
  • This query doesn't work, and I launch the query only with _id and it is match, the problem is $set. – Izaskun Peña May 05 '16 at 14:43
  • Although work, the result would be the same as in my question, because the find returns a user and set $ crushes me array and make a push – Izaskun Peña May 05 '16 at 14:45
0

You can use the $ - positional operator for the update:

db.collection('users').update({
    "_id": ObjectId("56cb877e73da764818ec5ded"),
    "githubtoken.username": "xxx"
}, {
    $set: {
        "githubtoken.$.username": username,
        "githubtoken.$.token": token
    }
});

And this should do the trick. More details on usage of $ - positional operator https://docs.mongodb.org/manual/reference/operator/update/positional/

Alexandru Olaru
  • 6,842
  • 6
  • 27
  • 53
  • Mongoose return me error: The positional operator did not find the match needed from the query.Unexpanded update: githubtoken.$.token. – Izaskun Peña May 05 '16 at 14:27
0

I found the solution in this page:

query = {"githubtoken" :{$elemMatch: {"username": username}}};


            update = {$set : {
                "githubtoken.$.username": username,
                "githubtoken.$.token": token
            }};

Thanks for the help :D

Community
  • 1
  • 1
Izaskun Peña
  • 177
  • 2
  • 4
  • 14