javascript - 更新 JSON 数组 (Mongoose) 内具体 JSON 对象中的特定字段

标签 javascript arrays json node.js mongodb

我正在尝试使用 Mongoose 更新 JSON 数组内的具体 JSON 对象中的特定字段。 我的 MongoDB 包含:

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

我想获取与 "username": "yyy""user._id"= "56cb877e73da764818ec5ded" 匹配的 JSON 对象,并将其 token 更改为"token": "4529zzz" 与 Mongoose ,如下所示:

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

数据库的架构是:

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

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

});

更新方法:

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

在我的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{

}});

但它不起作用,因为删除所有 githubtokens 数组并仅推送新的 githubtoken,如下所示:

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

有什么想法吗? 非常感谢您:D

最佳答案

您可以使用 $ - 位置运算符进行更新:

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

这应该可以解决问题。有关 $ - 位置运算符 使用的更多详细信息 https://docs.mongodb.org/manual/reference/operator/update/positional/

关于javascript - 更新 JSON 数组 (Mongoose) 内具体 JSON 对象中的特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37040734/

相关文章:

java - 如何在 Json 数组中创建 Json 数组?

javascript - 如何管理带有父字段和子字段的表单的显示

java - Jackson JSON 解析器无效的 utf-8 起始字节

sql - Postgres 从 jsonb 数组中获取值匹配的所有元素

javascript - 在合并对象的键中创建值数组

arrays - Golang,将嵌入式结构转换为数组

javascript - 如何按日期计算对象数组中的出现次数

javascript - 将值从按钮传递到输入值

javascript - 如何通过 AJAX 调用获取 google plus 按钮计数

javascript - 如何缩短 jQuery 函数?