簡體   English   中英

Mongoose 填充對自己架構的引用

[英]Mongoose populate reference to own Schema

我在那里有一個貓鼬模式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 后在數據庫中看到用戶 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 在數據庫中顯示正常......

建議的重復並沒有真正幫助我,因為我什至不使用那么多嵌套,問題可能只是模式自引用

有任何想法嗎? 提前致謝!

好的,我找到了問題所在。 user.profile是來自 Mongoose 的虛擬模式。 所以我擴展了:

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

現在friends的填充工作!

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);
  });

嘗試僅使用必填字段(不包括“朋友”字段)填充朋友,以避免自引用模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM