为什么我不能在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) { console.log(item); test.total += item; }); console.log(test.total);
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 }
就像应该。
或者,至less提供架构默认值。
var testSchema = new Schema({ total: { type: Number, default: 0 } });
但是,如果什么都没有,那么值是undefined
,试图增加一个未定义的值只是返回没有结果。