Here is the structure of my model:
var userSchema = new mongoose.Schema(
{
userName: {type: String, required: true},
firstName: {type: String},
lastName: {type: String},
password: {type: String, required: true},
email: {type: String},
profileImg: String,
weight: {type:Array, default:[]},
schedules: {type: [schedule], default: []},
dateCreated: {type: Date, required: true, default: Date.now},
}
);
I'm encountering an issue with the 'weight' field which should only contain numbers. When trying to update and push a new number into it, I observe unexpected behavior on the server side:
var data = req.body;
var _id = req.params.userid.replace(new RegExp('"', 'g'), "")
User.findById(_id, fieldsFilter, function (err, user) {
if (err) return next(err);
console.log('*********', data.weight)
if (user) {
user.userName = data.userName ? data.userName : user.userName;
user.firstName = data.firstName ? data.firstName : user.firstName;
user.lastName = data.lastName ? data.lastName : user.lastName;
user.email = data.email ? data.email : user.email;
//TODO check if weight is in correct form
// HERE!!
user.weight = data.weight ? user.weight.push( data.weight) : user.weight;
user.save(onModelSave(res));
console.log(user.weight)
} else {
//user does not exist create it
var newUser = new User(data);
newUser._id = ObjectId(req.params.userid);
newUser.save(onModelSave(res, 201, true));
}
When looking at the log outputs, I see that data.weight has the value 5
, but after processing, the array contains just 1
.
I am struggling to identify the root cause of this inconsistency.
Your help is greatly appreciated.