[英]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.