简体   繁体   中英

Update a specific field in a croncrete JSON object inside an JSON array (Mongoose)

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

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

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM