如何使用 Mongoose 将带有 ID 数组的嵌套字段填充到另一个集合?

问题描述

我有两个系列。用户和事件。在我的事件模型中,我有一个对象“参加者”(“主持”、“待定”、“接受”、“拒绝”),其中包含引用用户的 ObjectId 数组。我正在尝试获取单个事件并填充用户信息。

我的事件架构

const EventSchema = new mongoose.Schema(
      {
        title: {
          type: String,required: true,},description: {
          type: String,eventDate: {
          type: Date,dateCreated: {
          type: Date,default: Date.Now,dateUpdated: {
          type: Date,attendees: {
          hosting: [
            {
              type: Schema.ObjectId,ref: "User",],pending: [
            {
              type: Schema.ObjectId,accepted: [
            {
              type: Schema.ObjectId,declined: [
            {
              type: Schema.ObjectId,

我的用户架构

const UserSchema = new mongoose.Schema(
  {
    name: {
      first: {
        type: String,last: {
        type: String,phone: {
      type: String,email: {
      type: String,match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,"Please add a valid email"],unique: true,password: {
      type: String,pictureUrl: String,allergies: [String],preferences: [String],favoriteRecipes: [String],events: {
      hosting: [
        {
          type: Schema.ObjectId,ref: "Event",pending: [
        {
          type: Schema.ObjectId,accepted: [
        {
          type: Schema.ObjectId,declined: [
        {
          type: Schema.ObjectId,

我查看了大量堆栈溢出,但找不到任何帮助。也许我需要改变我的模型?这是我的查询

db.Event.find({})
      .populate({
        path: "attendees.pending",model: "User",})
      .exec((err,docs) => {
        console.log(docs);
        process.exit(0);
      });

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)