无法通过mongoose更新单个属性

时间:2017-01-13 21:50:30

标签: node.js mongodb mongoose

Frist我已阅读并在mongoose-and-partial-select-update的帖子中尝试解决方案。 但是,当我尝试使用传统样式时,查询会起作用。

我的架构:

var userSchema = mongoose.Schema({
    local: {
        email: {
            type: String,
            index: {
                unique: true,
                dropDups: true
            }
        },
        password: String,
        displayName: String,
        avatar: {
            type: String,
            default: "./img/user.png"
        },
        role: {
            type: String,
            default: "student"
        },
        ask_history: [
            {
                question_id: {
                    type: mongoose.Schema.Types.ObjectId,
                    ref: 'questionAnswer'
                },
                favorite: Boolean,
                ask_time: Date
            }
        ],
        interest: [String]
    }
})

工作更新功能:

User.findById(id, function(err, User) {
            if (err) {
                throw done(err);
            }
            if (!User) {
                return;
            }
            User.local.role = "admin";
            User.save(function(err, updatedUser) {
                if (err) {
                    throw err
                } else {
                    //good
                }
            })
        });

但是,如果我这样做:

User.update({_id : id},
  {$set{
      local:{role:"admin"}
     }
  },function(...){...}
});

上面的代码会将用户覆盖为:

{
  _id : "...",
  local: {
          role : "admin"
         }
}

我读到$只会更新属性,我做错了吗?

1 个答案:

答案 0 :(得分:2)

位置运算符$使用子文档数组。

在您的情况下,您只有一个子文档,因此以下内容应该有效:

User.update({_id : id},
    { $set
        {
            "local.role": "admin"
        }
    }, function(...){...}
});
相关问题