Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an attribute to an existing document with Mongoose?

I have an existing user object in the database.

I've modified my models/user.js to add an attribute "isAdmin" to the User schema.

  , isAdmin     : { type: Boolean, default: false }

But now when I save the document (ie: I update my profile). The isAdmin attribute shows up when I console.log(user) in my app...(it is false as expected)...but when I goto the mongo db console directly, it is not present in the existing document.

If I create a new user object, the isAdmin attribute IS present in the new doc. How can I add this attribute to an existing document so that it shows up in the db directly?

edit: i've decided to add a role attribute and just modify the particular user setting their role to admin in robomongo instead of using mongoose to do it.

like image 511
chovy Avatar asked Nov 12 '22 12:11

chovy


1 Answers

I agree with Hector regarding writing your code to treat a missing isAdmin field the same as it being set to false instead of bothering with this.

But if you wanted it done, one way would be to explicitly mark isAdmin as modified so that the subsequent call to save would write out the default value:

doc.markModified('isAdmin');
doc.save();
like image 158
JohnnyHK Avatar answered Nov 15 '22 04:11

JohnnyHK