【问题标题】:Mongoose populate reference to own SchemaMongoose 填充对自己 Schema 的引用
【发布时间】:2015-07-01 21:23:29
【问题描述】:

我有一个猫鼬模式User 和一个字段friends,它再次引用User 模式,如下所示:

var UserSchema = new Schema({
  name: String,
  email: { type: String, lowercase: true },
  role: {
    type: String,
    default: 'user'
  },
  friends: [{ type: Schema.Types.ObjectId, ref: 'User'}]
});

这很好用,我可以像这样设置其中一些后在数据库中看到用户 ID:

var test = new User({...});
var admin = new User({...});
var users = [test, admin];

User.find({}).remove(function () {
  User.create(users, function () {
    console.log('finished populating users');
  });
});

但现在我想在获取单个用户时填充 friends 字段,就像在文档中一样,我这样做:

exports.show = function (req, res, next) {
  var userId = req.params.id;

  User.findById(userId)
    .populate('friends')
    .exec(function (err, user) {
      if (err) return next(err);
      if (!user) return res.send(401);
      res.json(user.profile);
    });
};

但我只是恢复了正常/未填充的用户 ID!

我感觉这是因为用户架构的自引用,但 ID 在数据库中显示良好...

建议的副本并没有真正帮助我,因为我什至没有使用那么多嵌套,问题可能只是架构的自引用

有什么想法吗?提前致谢!

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

好的,我发现问题出在哪里了。 user.profile 是来自 Mongoose 的虚拟模式。所以我扩展了它:

UserSchema
  .virtual('profile')
  .get(function() {
    return {
      '_id': this._id,
      'name': this.name,
      'role': this.role,
      'friends': this.friends
    };
  });

现在friends 的填充工作正常!

【讨论】:

    【解决方案2】:
    User.findById(userId)
     .populate('friends', ['name', 'email'])
     .exec(function (err, user) {
       if (err) return next(err);
       if (!user) return res.send(401);
       res.json(user.profile);
      });
    

    尝试仅使用必填字段(不包括“朋友”字段)填充朋友以避免架构的自引用。

    【讨论】:

    • 这听起来合乎逻辑。我猜它也试图填充“朋友”的“朋友”?
    • 让我知道这是否可行……如果可行,请接受/支持我的回答。
    • 终于有时间测试了,但还是不行... :-/
    • 嘿,我想通了。请参阅下面的答案!
    猜你喜欢
    • 2022-06-14
    • 1970-01-01
    • 2017-07-13
    • 2017-10-27
    • 2019-01-08
    • 2017-03-29
    • 1970-01-01
    • 2013-07-08
    • 2017-02-10
    相关资源
    最近更新 更多