MongoDB父母/孩子关系和父母的快速检索

时间:2019-01-04 08:29:34

标签: node.js mongodb mongoose

我的猫鼬有以下型号,Book属于User。 当我Book.findAll()时,我还想从关联的用户中检索信息。实现此目标的最佳方法是什么?

const user_schema = new mongoose.Schema({
  fullname: { type: String },
  avatar: { type: String }
});
module.exports.User = mongoose.model("User", user_schema);


const book_schema = new mongoose.Schema({
  _uid: { type: ObjectId, ref: "User", required: true },
  title: { type: String, required: true }
  text: { type: String, required: true }
});

module.exports.Book = mongoose.model("Book", book_schema);

我需要能够执行以下操作:

Book.findOne({...}).user.avatar

1 个答案:

答案 0 :(得分:1)

您可以使用$lookup进行此类操作。

db.books.aggregate([
   {
     $lookup:
       {
         from: "users",
         localField: "user_id", //User ID in users collection
         foreignField: "_uid",  //User ID in books collection
         as: "books_data"
       }
  }
])

此外,请在两个模式中都具有主键值:

const user_schema = new mongoose.Schema({
  user_id : {type : String },
  fullname: { type: String },
  avatar: { type: String }
});
相关问题