Express:推送模型阵列中的元素

时间:2015-12-23 14:12:28

标签: javascript express

我有这个型号:

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},
    }
);

正如你所看到我有一个必须包含数字的字段'权重',当我尝试做一个put并在其中推送一个新数字时我有一些奇怪的行为,这是服务器端:

  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));
        }

正如您所看到的,我有两个控制台日志和data.weight的值为5,这是打印的输出:

********* 5
[1]

所以在数组中存储1? 我无法理解问题出在哪里。

提前谢谢

1 个答案:

答案 0 :(得分:4)

问题在于:

user.weight = data.weight ? user.weight.push( data.weight) : user.weight;

如果存在data.weight,则您将user.weight的结果分配给user.weight.push()。哪个是new length of the array(如果之前user.weight为空,则为1)。

看起来你想要这个:

if (data.weight) {
  user.weight.push(data.weight);
}