Javascript';如果';查看表单字段中是否有数字?

Javascript';如果';查看表单字段中是否有数字?,javascript,node.js,angularjs,mongodb,mongoose,Javascript,Node.js,Angularjs,Mongodb,Mongoose,我在Mongoose模式中有一些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

我在Mongoose模式中有一些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">
因为
console.log(请求主体位置)是否记录号码

尝试以下操作:

// if 'position' is not filled in, fill it in
// not using !position because 0 might be a valid value
if( (parseFloat(position) || -1) == -1) {
// code for auto-incrementing

parseFloat()将根据浏览器的使用年限返回null或NaN。如果传递了错误值(NaN,未定义)或null,“or”函数将返回次函数(在本例中为-1)。您可以通过更改将-1值更改为您想要的任何值。我喜欢数字,因为它们占用的内存比字符串少几个字节,处理速度也更快。

不清楚代码是如何/何时执行的,以及所有内容之间是如何相互关联的。如果不清楚代码的作用,很难提供帮助。如果从HTML元素填充
position
,则它将是一个字符串值。在Stack Overflow上有很多关于检查一个值是否是一个数字的帖子。我猜
position
就是这个值,而它总是一个字符串,所以检查typeof失败得很惨。您希望
isNaN
位置在猫鼬模型中定义为一个数字,但这没有什么区别吗<代码>位置:编号,
@FelixKling添加了上下文以使代码清晰。。这是否更有帮助?这将返回ReferenceError:控制台中未定义位置,以及浏览器网络上的500内部服务器错误。。谢谢
// if 'position' is not filled in, fill it in
// not using !position because 0 might be a valid value
if( (parseFloat(position) || -1) == -1) {
// code for auto-incrementing