How can I add an attribute to an existing document using Mongoose?

I have an existing custom object in the database.

I modified my /user.js models to add the "isAdmin" attribute to the user schema.

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

      

But now that I save the document (i.e. update my profile). The isAdmin attribute shows up when I use console.log (user) in my application ... (it is false as expected) ... but when I immediately get the mongo db console, it is not in the existing document.

If I create a new user object, the isAdmin attribute is present in the new document. How do I add this attribute to an existing document so that it appears directly in the db?

edit: I decided to add an attribute role

and just change the specific user by setting their role admin

in robomongo instead of using mongoose to do it.

+3


source to share


2 answers


just update existing docs in mongo shell to add new property.



0


source


I agree with Hector regarding writing your code to handle the missing field the isAdmin

same way it was set to false

instead of worrying about it.

But if you want to, one way would be to explicitly mark isAdmin

as modified so that a subsequent call will save

write out the default:



doc.markModified('isAdmin');
doc.save();

      

+1


source







All Articles