XYZ_Allen
XYZ_Allen

Reputation: 323

Failed to update single property by mongoose

Frist I have read and try the solution in the post of mongoose-and-partial-select-update. However when I try to use the traditional style, query would work.

My schema:

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]
    }
})

Working Update function:

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

However if I do this:

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

Code above will overwrite user into:

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

I read that $ will make the update only changing property, where I did wrong?

Upvotes: 1

Views: 43

Answers (1)

Santanu Biswas
Santanu Biswas

Reputation: 4787

The positional operator $ works with array of subdocuments.

In your case you have a single sub-document, so the following should work:

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

Upvotes: 2

Related Questions