Reputation: 19268
In the following code, the user isn't getting saved.
router.patch('/onboard', auth.requireLoggedIn, function (req, res) {
if (req.user.settings.onboarding[req.body.page]) {
res.status(409).json({
status: 'Error: Trying to onboard for a page that has already been onboarded.',
});
}
console.log(req.body.page);
req.user.settings.onboarding[req.body.page] = true;
console.log(req.user.settings.onboarding);
req.user
.save()
.then(function (res) {
console.log(res);
res.status(200).json({
status: 'Successful',
});
})
.catch(function () {
res.status(500).json({
status: 'Internal server error.',
});
})
;
});
req.user.settings.onboarding.equityCalculator
starts off as false
and I want to set it as true
. All of the console logs indicate that this is happening. However, when I check my database, it isn't updated.
By "check my database" I mean "look in Robo 3T". But I also mean querying the database and looking at the user I get back.
Furthermore, the following code works perfectly. I don't see how this code works but the code above does not work.
router.patch('/subscribe-to-email', auth.requireLoggedIn, function (req, res) {
if (req.user.emailOptIn) {
res.status(409).json({
status: 'You can\'t subscribe if you are already currently subscribed.',
});
}
req.user.emailOptIn = true;
req.user
.save()
.then(function () {
res.status(200).json({
status: 'Successful',
});
})
.catch(function () {
res.status(500).json({
status: 'Internal server error.',
});
})
;
});
Here is the relevant part of my User schema:
UserSchema = new mongoose.Schema({
emailOptIn: {
type: Boolean,
default: false,
required: true,
},
settings: {
type: mongoose.Schema.Types.Mixed,
required: true,
default: defaultSettings,
},
...
});
Upvotes: 0
Views: 1118
Reputation: 368
Try the following, it worked for me in a similar situation:
req.user.settings.onboarding[req.body.page] = true;
req.user.markModified('settings.onboarding');
req.user.save()
The lack of saving seems to occur when setting array indices, like in your example. Marking the modified array allows the saving to occur properly.
Upvotes: 1