Mongoose: 架构、数组、默认值(默认值“[]”不起作用)

创建于 2011-02-15  ·  6评论  ·  资料来源: Automattic/mongoose

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/dbTest');

var arrayTestSchema = new Schema({
    anArray: {
      type: Array,
      'default': []
    }
});

mongoose.model('ArrayTest', arrayTestSchema);
ArrayTest = mongoose.model('ArrayTest');

var myTest = new ArrayTest();
console.log(arrayTestSchema.anArray);

mongoose.connection.close();

显示“未定义”

最有用的评论

它失败是因为您没有访问您的文档实例。 我已经注释掉了您的 console.log 并将其替换为正确的。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/dbTest');

var arrayTestSchema = new Schema({
    anArray: {
      type: Array,
      'default': []
    }
});

mongoose.model('ArrayTest', arrayTestSchema);
ArrayTest = mongoose.model('ArrayTest');

var myTest = new ArrayTest();
// console.log(arrayTestSchema.anArray);
console.log(myTest.anArray);

mongoose.connection.close();

所有6条评论

至少在 master 中,这对我来说很好用......除了它返回一个 MongooseArray 所以它充满了许多其他疯狂:) 不仅仅是价值。

你运行的是什么版本?

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/dbTest');

var arrayTestSchema = 新架构({

 Title: String,
 Description: String,
 Status: String

});

mongoose.model('ArrayTest', arrayTestSchema);
ArrayTest = mongoose.model('ArrayTest');

var myTest = new ArrayTest();

myTest.Title = '项目';
myTest.Description = '使用 mongodb 和节点';
myTest.Status = '打开';

控制台日志(我的测试);

猫鼬.connection.close();

我正在运行 1.0.12,npm 版本。
应该是主版本,因为我看到昨天发布了 1.0.12。

不要理解你想指出 pradeepthundiyil 什么。

它失败是因为您没有访问您的文档实例。 我已经注释掉了您的 console.log 并将其替换为正确的。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/dbTest');

var arrayTestSchema = new Schema({
    anArray: {
      type: Array,
      'default': []
    }
});

mongoose.model('ArrayTest', arrayTestSchema);
ArrayTest = mongoose.model('ArrayTest');

var myTest = new ArrayTest();
// console.log(arrayTestSchema.anArray);
console.log(myTest.anArray);

mongoose.connection.close();

大声笑,好吧,我明白了,昨天对我来说是糟糕的一天。 感谢您指出这一点 =)

@bnoguchi数组项的类型呢?

此页面是否有帮助?
0 / 5 - 0 等级