简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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