2016-09-20 69 views
0

我看到很多关于这个问题,但我找不到什么是错的。当我使用填充来获取“外键”时,我的字段未定义。猫鼬填充不确定的领域

用户模型

var userSchema = new Schema({ 
    email  : { type: String, required: true, unique: true }, 
    password  : { type: String, required: true }, 
    firstname : { type: String, required: true }, 
    lastname  : { type: String, required: true }, 
    created_at : Date, 
    updated_at : Date, 
    office  : [ { type: Schema.Types.ObjectId, ref: 'Office' } ] 
}); 

var User = mongoose.model('User', userSchema, 'User'); 

module.exports = User; 

办公模式:

var officeSchema = new Schema({ 
    name  : { type: String, required: true }, 
    address  : String, 
    city  : String, 
    geolocation : [ { type: Schema.Types.ObjectId, ref: 'Geolocation' } ], 
    company  : [ { type: Schema.Types.ObjectId, ref: 'Company' } ] 
}); 

var Office = mongoose.model('Office', officeSchema, 'Office'); 

module.exports = Office; 

填充代码:

User.find({}) 
.populate('office') 
//.populate('office', 'name') I tried this too 
.exec(function (err, users) { 
    if (err) return handleError(err); 

    users.forEach(function(user){ 
     console.log('Office name: ', user.office.name); 
    }); 
}); 

我想获取用户办公室名称。但是这个user.office.name返回我undefined,当我这样做user.office我可以看到名称字段的对象。但是我没有访问名称字段的权限。

+1

'user.office'字段是模式中的数组。试试'user.office [0] .name'等。 –

+0

不错,你说得对!我可以更改我的模型以使用不带数组的填充吗?它会工作吗? – John

+0

您可以通过删除'['&']'在模式级别轻松更改它。 –

回答

2

userSchemaoffice字段被定义为阵列。因此,为了访问它的元素,使用user.office[0].nameuser.office[1].name

否则,使用一个循环:

user.office 
    .forEach(function(each) { 
     console.log('Office name: ', each.name); 
    }); 
+0

谢谢。我有一个关于填充的问题。正如你可以在我的officeSchema中看到的,我拥有公司和地理位置对象ID。当我填充办公室时,可以在用户查找时填充这两个对象? – John

+1

@John http://stackoverflow.com/questions/12821596/multiple-populates-mongoosejs – SkyQ

+0

是的,你可以。查看[Mongoose Deep Populate](https://github.com/buunguyen/mongoose-deep-populate)插件,或者查看Mongoose [跨越多个级别](http://mongoosejs.com/文档/ populate.html)。 –

1

你只需要编辑您的查询

populate({path: "office", populate: {path:"company"}}) 

这我们也会填充公司数据。

+0

噢,很好,我可以用'user.office.company.name'来抓它,它的工作原理非常感谢。但是,你知道与SQL关系相比,猫鼬填充性能是否真的很好? – John

+0

@John当然是mongo,是文档数据库,mongo的性能比SQL关系好。如果你喜欢答案,请稍等。 –

+0

噢,好的。我听说SQL更好地管理两个表之间的关系。所以如果NoSQL足够好,我会留在Mongo上 – John