Javascript 为什么我能';猫鼬/猫鼬B中的t增量?
我试图增加,但结果总是显示它是未定义的Javascript 为什么我能';猫鼬/猫鼬B中的t增量?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我试图增加,但结果总是显示它是未定义的 var mongoose = require('mongoose'); var TestSchema = mongoose.Schema({ total: Number }); var Test = mongoose.model('Test', TestSchema); var arr = [2,4,5,6,7,8]; var test = new Test(); arr.forEach(function(item) { co
var mongoose = require('mongoose');
var TestSchema = mongoose.Schema({
total: Number
});
var Test = mongoose.model('Test', TestSchema);
var arr = [2,4,5,6,7,8];
var test = new Test();
arr.forEach(function(item) {
console.log(item);
test.total += item;
});
console.log(test.total);
console.log(test.total)
将打印出未定义的内容。它不起作用,因为没有定义“total”的开头。因此,请定义以下内容:
var mongoose = require('mongoose');
var TestSchema = mongoose.Schema({
total: Number
});
var Test = mongoose.model('Test', TestSchema);
var arr = [2,4,5,6,7,8];
var test = new Test();
arr.forEach(function(item) {
console.log(item);
test.total += item;
});
console.log(test.total);
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var testSchema = new Schema({
total: Number
});
var Test = mongoose.model( 'Test', testSchema );
var arr = [2,4,5,6,7,8];
var test = new Test({ "total": 0 });
arr.forEach(function(item) {
console.log(item);
test.total += item;
});
console.log(test);
产出:
2
4
5
6
7
8
{ _id: 5641850e7a8c9b001842c6d2, total: 32 }
就像它应该做的那样
或者,至少提供一个模式默认值
var testSchema = new Schema({
total: { type: Number, default: 0 }
});
但是,如果没有任何内容,那么该值是未定义的,并且尝试递增未定义的值只会在结果中返回任何内容。哦,天哪,我几乎忘记了我必须定义它,即使它是数字类型。如果我没有弄错的话,其他编程语言(如Java)将数字字段默认定义为零。