我有一个包含 2 个字符串属性数组和其他一些属性的 Mongoose 模型:
var Model = new Schema({
_id: {type: Number, required: true, unique: true},
name: {type: String, required: true},
oneList: [String],
anotherList: [String]
});
我创建模型:
var model = new Model({
_id: 1,
name: 'model',
oneList: ['a', 'b'],
anotherList: ['c', 'd']
})
但是当我检查模型时,所有列表都未定义:
model._doc === {
_id: 1,
name: 'model',
oneList: undefined,
anotherList: undefined
}
我尝试了一些变化:
- 将模型定义从 [String] 更改为 [ ]
- 在模型外部单独创建数据然后传递它
- 创建不带列表数据的模型,然后将其添加到模型
即使我创建一个空模型:
var model = new Model({})
model._doc.oneList === undefined
model._doc.anotherList === undefined
上下文: 问题发生在 docker 容器上,但不在我的本地计算机上
Node :v4.4.7
Mongoose :v4.6.0
最佳答案
我遇到了同样的问题,显然当你的模型中有一个嵌套数组时, Mongoose 有一个 open issue 1335当属性引用架构时,它会保存一个空数组。我尝试使用预保存来强制属性为空数组(如果属性的长度为 0 或未定义)。
在属性架构中指定 unique=true
时也要小心,因为空或未定义的属性将违反索引并引发错误。
注意:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var barSchema = new mongoose.Schema({
baz: String
});
var fooSchema = new mongoose.Schema({
bars: [barSchema]
});
var Foo = mongoose.model('Foo', fooSchema);
var foo = new Foo();
console.log(foo); // { _id: 55256e20e3c38434687034fb, bars: [] }
foo.save(function(err, foo2) {
console.log(foo2); // { __v: 0, _id: 55256e20e3c38434687034fb, bars: [] }
foo2.bars = undefined;
foo2.save(function(err, foo3) {
console.log(foo3); // { __v: 0, _id: 55256e20e3c38434687034fb, bars: undefined }
Foo.findOne({ _id: foo3._id }, function(err, foo4) {
console.log(foo4); // { _id: 55256e20e3c38434687034fb, __v: 0, bars: [] }
mongoose.disconnect();
});
});
});
关于javascript - 创建包含数组类型的 Mongoose 模型对于我的 docker 容器中的那些类型返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534919/