【发布时间】:2014-05-18 08:14:13
【问题描述】:
如果表单字段中没有手动输入数字,我在 Mongoose Schema 中有一些 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
自动递增运行良好,但无论字段中是否有数字,它都会这样做。什么是更好的“if 语句”?
我在前端有这个表单域:
<input type="number" class="form-control input-lg text-center" placeholder="Position" ng-model="formData.position">
而且我知道数据是通过 via
position : req.body.position,
因为console.log(req.body.position); 确实记录了号码
【问题讨论】:
-
不清楚你的代码是如何/何时执行的,以及一切是如何相互关联的。如果没有清楚地了解代码的作用,就很难提供帮助。
-
如果
position是从 HTML 元素填充的,它将是一个 字符串值。 Stack Overflow 上有很多关于检查值是否为数字的帖子。 -
我猜
position是值,而且它始终是一个字符串,所以检查 typeof 失败得很惨。你想要isNaN -
位置在 Mongoose 模型中被定义为一个数字,但这没有区别吗?
position: Number, -
@FelixKling 为代码清晰添加了上下文.. 这更有帮助吗?
标签: javascript node.js angularjs mongodb mongoose