[英]Why i can't increment in mongoose / mongodb?
我试图增加但结果总是显示它是未定义的。
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 }
就像它应该的那样。
或者,至少提供一个架构默认值。
var testSchema = new Schema({
total: { type: Number, default: 0 }
});
但是如果什么都没有,那么该值是undefined
并且试图增加一个未定义的值只会在结果中不返回任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.