Javascript 猫鼬模式设计
我做了以下工作:Javascript 猫鼬模式设计,javascript,schema,mongoose,Javascript,Schema,Mongoose,我做了以下工作: var peoples = db.model('peeps', new mongoose.Schema()); peoples.find({}, {weights: 1}).exec(function(err, data) { // data is an array with objects data.forEach(function(el, index, array) { console.log(el); // --> {weights: [{weigh
var peoples = db.model('peeps', new mongoose.Schema());
peoples.find({}, {weights: 1}).exec(function(err, data) {
// data is an array with objects
data.forEach(function(el, index, array) {
console.log(el); // --> {weights: [{weight: 45.78, diet: ln}, {weight: 21.89, diet: lgt}]}
consoel.log(el.weights) // --> undefined
} ... });
但当我提出这样的模式时:
var peoples = db.model('peeps', new mongoose.Schema({
weights: []
}));
peoples.find({}, {weights: 1}).exec(function(err, data) {
// data is an array with objects
data.forEach(function(el, index, array) {
console.log(el); // --> {weights: [{weight: 45.78, diet: ln}, {weight: 21.89, diet: lgt}]}
consoel.log(el.weights) // --> [[object Object], [object Object]]
} ... });
然后,第二个允许我通过el.weights[0].weight
这是mongoose设计的差异,还是我在访问数组中对象的第一块代码中做错了什么
模式/数据的示例如下所示:
{ _id: 0,
spname: 'INDV_748',
weights:
[ { weight: 1.463179736705023, diet: 'ln' },
{ weight: 11.78273309957772, diet: 'lgt' } ] }
如果我没有在新mongoose.Schema({…})
中指定\u id:Number
,那么对于上述两种情况,\u id
将不会显示在任何find()
查询中
这也是设计的一部分吗?这令人困惑。这些
find
查询不应返回查询选择器为{weights:1}
的任何文档,因为weights
是一个对象数组,而不是1
。而且您的forEach
调用的语法没有意义。复制了错误的语法。谢谢。似乎是我所期望的;架构中未包含的字段不会获得完全支持。如果您没有定义\u id
,则假定它是一个ObjectID,这在您的情况下是不正确的。是否有引用?关于\u id
的部分是,但您试图访问架构中定义之外的字段,这是越界的。