Nat
Nat

Reputation: 1762

How to add new values into existing MongoDB database even when it's not specified in original model

I have a pretty average database to store your average data, like emails and usernames.

I'm creating this database/backend with Node.JS and Mongoose/MongoDB. I would like to make it future proof. At the moment, I have a User model with values I think I'll only need, however, I know for a fact that I will have to add values into the user's database (that's not specified in the model) later on down the line.

Obviously, since the user has already been created using the model, I don't want to mess up their data. I use the model to search for a user by their ID when they make a request, but then I just want to add a value and some data into the JSON document. The data to be added could be in the root of their JSON data, or a nested value in their JSON document, so I'd like to know how to do both.

My data structure according to my model present follows:

user: 
    {
     username: "",
     email: "",
     isVerified: "",
     password: "",
     hub: {
             isSetup: true,
             swVersion: 0.0`
    }
}

The code to update EXISTING data (in the example below, I updated the nested JSON's - 'hub' value 'isSetup' to true:

User.update({_id: req.user.id}, {$set: { "hub.isSetup" : true}})
.then((data) => {
    return res.json({message: data});
})
.catch(err => {
   // log.error(err);
    return next({message: 'Error updating User.'});
});

How would I add data, like above, to an existing document to the database, without being lockdown to the model used to search the user, the model is 'User'.....used: User.update(...) as I have only found, in both my testing and searching google, that I can only add data into the database as long as the model specifies it - which I do not want to do.

Thanks

Upvotes: 1

Views: 187

Answers (1)

Dom
Dom

Reputation: 734

What you're looking for is the strict mode option. https://mongoosejs.com/docs/guide.html#strict

If you specify it as false, you can add whatever you like.

Upvotes: 1

Related Questions