gpt4 book ai didi

javascript - Express:将元素推送到模型的数组中

转载 作者:行者123 更新时间:2023-11-30 09:55:08 25 4
gpt4 key购买 nike

我有这个模型:

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

如您所见,我有一个必须包含数字的“重量”字段,当我尝试在其中进行放置和推送新数字时,我有一些奇怪的行为,这是服务器端:

  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?我不明白问题出在哪里。

提前致谢

最佳答案

问题是这样的:

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

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

看起来你想要这个:

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

关于javascript - Express:将元素推送到模型的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com