我有一个在猫鼬模式的JavaScript来自动增加一个值,如果没有在表单字段中手动输入数字。Javascript'如果'查看表单域是否有数字?
// before validation starts, the number of Items is counted..afterwards, the position is set
ItemSchema.pre("validate", function(next) {
var doc = this;
// if 'position' is not filled in, fill it in..not using !position because 0 might be a valid value
if(typeof position !== "number") {
// count the number of Items *
// use mongoose.model to fetch the model because the model is not compiled yet
mongoose.model("Item").count(function(err, num) {
// if there was an error, pass it to next()
if(err)
return next(err);
// set the position, then call next();
doc.position = num;
return next();
});
} else if(this.isModified("position") || this.isNew()) {
// code to check if there is an existing document with the same position
// code to check move down other document positions, if existing
自动递增工作正常,但它是这样做的,无论该字段中是否有数字。什么是更好的“如果陈述”通过?
我有这个表单域的前端:
<input type="number" class="form-control input-lg text-center" placeholder="Position" ng-model="formData.position">
而且我知道数据是通过
position : req.body.position,
因为console.log(req.body.position);
不登录数量
目前还不清楚你的代码是如何/何时执行的,以及每个事物如何相互关联。如果不清楚您的代码的作用,很难提供帮助。 –
如果'position'从HTML元素中填充,它将是一个*字符串值*。在Stack Overflow上有很多关于检查值是否是数字的帖子。 –
我猜'position'是值,并且总是一个字符串,因此检查typeof失败。你想'isNaN' – adeneo