简体   繁体   English

为什么我不能在 mongoose / mongodb 中增加?

[英]Why i can't increment in mongoose / mongodb?

Im trying to increment but the result always shows that it is undefined.我试图增加但结果总是显示它是未定义的。

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) will printout undefined. console.log(test.total)将打印输出未定义。

It doesn't work because "total" is not defined to start with.它不起作用,因为开始时没有定义“总计”。 So instead define something:所以改为定义一些东西:

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);

Outputs:输出:

2
4
5
6
7
8
{ _id: 5641850e7a8c9b001842c6d2, total: 32 }

Just like it should.就像它应该的那样。

Alternately, at least supply a schema default.或者,至少提供一个架构默认值。

var testSchema = new Schema({
  total: { type: Number, default: 0 }
});

But if nothing is there, then the value is undefined and trying to increment an undefined value just returns nothing in result.但是如果什么都没有,那么该值是undefined并且试图增加一个未定义的值只会在结果中不返回任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM