【问题标题】:Mongoose populate undefined fieldsMongoose 填充未定义的字段
【发布时间】:2017-01-28 03:04:13
【问题描述】:

我看到很多关于此的问题,但我找不到问题所在。当我使用填充获取“外键”时,我的字段未定义。

用户模型

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 返回我未定义,当我这样做user.office 时,我可以看到带有名称字段的对象。但我无权访问名称字段。

【问题讨论】:

  • user.office 字段是架构中的一个数组。试试user.office[0].name
  • 很好,你说得对!我可以更改我的模型以使用没有数组的填充吗?它会工作吗?
  • 您可以通过删除 [] 在架构级别轻松更改它。
  • 而不是 find() 使用 findOne()。它将在 Object 中返回一条记录。

标签: javascript node.js mongodb mongoose mongoose-populate


【解决方案1】:

您只需将查询编辑为

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

它还会填充公司数据。

【讨论】:

  • 很好,我可以用user.office.company.name 抓住它,谢谢。但是你知道mongoose填充性能相比SQL关系是否真的好?
  • @John 当然 mongo 是文档数据库,mongo 的性能优于 SQL 关系。如果您喜欢答案,请点赞。
  • 哦,好的。我听说 SQL 更适合管理两个表之间的关系。因此,如果 NoSQL 足够好,我会继续使用 mongo
【解决方案2】:

userSchema 中的office 字段定义为数组。因此,为了访问其元素,请使用user.office[0].nameuser.office[1].name 等。

否则,使用循环:

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

【讨论】:

  • 谢谢。我有一个关于填充的问题。正如您在我的 officeSchema 中看到的,我有公司和地理位置对象 ID。当我填充办公室时,是否可以同时在我的用户查找上填充这两个对象?
  • 是的,你可以。查看 Mongoose Deep Populate 插件,或者您可以查看 Mongoose populates across multiple levels 的方式。
  • @Westen 我不是这种情况。我不在同一个模式中。用户架构不知道公司架构。所以我认为 Mongoose Deep Populate 插件是目前最好的解决方案
猜你喜欢
  • 2012-01-22
  • 2017-05-21
  • 1970-01-01
  • 2013-07-06
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
相关资源
最近更新 更多