javascript - 无法让 populate() 填充 Mongoose 中的数组

标签 javascript node.js mongodb express mongoose

首先我要说的是,我知道这似乎是一个常见问题,我花了几天时间试图解决这个问题,但似乎没有答案,所以我在这里尝试一下。

我有两个模型,用户章节:章节可以有许多成员(用户) 。当我执行router.get('/chapters')时,我希望看到与章节关联的所有用户的数组作为属性以及其他Chapter属性,如下所示:

[
    {
        "leads": [],
        "members": [
           {"_id":"someString1","firstName":"...", "lastName":"..."},
           {"_id":"someString2","firstName":"...", "lastName":"..."},
        ],
        "date": "2018-12-12T15:24:45.877Z",
        "_id": "5c11283d7d13687e60c186b3",
        "country": "5c11283d7d13687e60c185d6",
        "city": "Buckridgestad",
        "twitterURL": "qui",
        "bannerPic": "http://lorempixel.com/640/480/people",
        "__v": 0
    }
]

但是我得到的是这样的:

  [
        {
            "leads": [],
            "members": [],
            "date": "2018-12-12T15:24:45.877Z",
            "_id": "5c11283d7d13687e60c186b3",
            "country": "5c11283d7d13687e60c185d6",
            "city": "Buckridgestad",
            "twitterURL": "qui",
            "bannerPic": "http://lorempixel.com/640/480/people",
            "__v": 0
        }
    ]

这些是我的架构:

章节

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Schema
const ChapterSchema = new Schema({
  country: {
    type: Schema.Types.ObjectId,
    ref: "countries"
  },
  city: {
    type: String,
    required: true
  },
  leads: [
    {
      type: Schema.Types.ObjectId,
      ref: "users"
    }
  ],
  members: [
    {
      type: Schema.Types.ObjectId,
      ref: "users"
    }
  ],
  twitterURL: {
    type: String,
    required: true
  },
  bannerPic: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now()
  }
});

module.exports = Chapter = mongoose.model("chapters", ChapterSchema);

用户

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  organisation: {
    type: String,
    required: true
  },
  chapter: {
    type: Schema.Types.ObjectId,
    ref: "chapters"
  },
  email: {
    type: String,
    required: true
  },
  admin: {
    type: Boolean,
    default: false
  },
  lead: {
    type: Boolean,
    default: false
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now()
  }
});

module.exports = User = mongoose.model("users", UserSchema);

就像我说的,当我调用端点时,我希望它返回所有章节以及所有用户作为填充属性。

我已经尝试了 .populate() 的很多变体,但要知道运气。我最接近的是经历回调 hell 的早期阶段,我知道这对于当今的技术来说是不必要的,但没有任何效果!

我的routes/api/chapters.js

// @route    GET api/chapters
// @desc     Get all Chapters
// @access   Public

router.get("/", (req, res) => {
  Chapter.find()
    .populate("members")
    .then(chapters => {
      return res.json(chapters);
    })
    .catch(err =>
      res.status(404).json({ nochaptersfound: "No Chapters found" })
    );
});

我可以让它以相反的方式工作:

我的routes/api/users.js

// @route    GET api/users
// @desc     Return all users
// @access   Public

router.get("/", (req, res) => {
  User.find()
    .populate("chapter")
    .exec()
    .then(users => res.status(200).json(users))
    .catch(err => console.log(err));

返回已填充章节的用户,但我无法填充chapter.members数组

任何帮助将不胜感激!

谢谢!!

最佳答案

根据您的评论,我相信您实际上并未在章节中存储用户。你正在做的是这样的:

User.create({..., chapter: id})...

假设章节现在有一个用户。这不是 Mongoose 的工作方式,所以如果你想在两个地方实际保存,你需要自己做。您正在将其视为关系数据库

您需要执行以下操作:

const user = await User.create({..., chapter: id})
const chapter = await Chapter.findOne({ _id: id })
chapter.members.push(user)
chapter.save()

如果你的填充不起作用,你不会得到一个空数组,你会得到一个带有 id 的数组。您当前的填充查询没问题,只是没有任何数据可供填充

有了 promise ,它看起来像这样:

var userPromise = User.create({..., chapter: id}).exec()
var chapterPromise = Chapter.findOne({ _id: id }).exec()
Promise.all([userPromise, chapterPromise]).then((user, chapter) => {
  chapter.members.push(user)
  return chapter.save()
}).then(chapter => {
  // send response
})

如果您需要 10 个章节和 10 到 50 个用户,我会创建 50 个用户,然后将所有用户推送到章节中并保存章节。

关于javascript - 无法让 populate() 填充 Mongoose 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53747075/

相关文章:

javascript - 根据元素的数量计算元素的价格

javascript - 如何使用 javascript 从域中删除子域

javascript - mocha.opts 已弃用,如何迁移到 package.json?

javascript - 循环nodejs中的setInterval

c# - .NET Core 使用 MongoDb 配置 OpenIddict

javascript - Youtube API V3 使用 PHP 获取横幅图像(未定义索引)

javascript - 转换为 JSON 时对象属性消失

javascript - jit-咕噜声 : Plugin for the "clean" task not found?

javascript - Mongoose 在填充后使用 where

javascript - 如何在 Express JS 中使用 router.post 使 POST 工作