首页 > 解决方案 > 填充包含对另一个集合的引用的集合数组返回空数组

问题描述

我有两个模型投票和链接,我试图在链接模型中填充投票数组,投票数组包含引用集合投票的 id,它只包含两个字段链接和用户,它们也引用下面提到的相同链接模型和分别是一个用户模型

链接架构:-

const linkSchema = new mongoose.Schema(
  {
    description: {
      type: String,
      trim: true,
    },
    url: {
      type: String,
      trim: true,
    },
    postedBy: {
      type: mongoose.Types.ObjectId,
      ref: "User",
    },
    votes: [{ type: mongoose.Types.ObjectId, ref: "Vote" }],
  },
  {
    timestamps: true,
  }
);

linkSchema.index({ description: "text" });
linkSchema.index({ createdAt: -1 });
module.exports = mongoose.model("Link", linkSchema);

投票模式:-

const mongoose = require("mongoose");

const voteSchema = new mongoose.Schema({
  link: { type: mongoose.Types.ObjectId, ref: "Link" },
  user: { type: mongoose.Types.ObjectId, ref: "User" }, 
});

module.exports = mongoose.model("Vote", voteSchema);

但是当我尝试获得链接的投票时,它总是返回一个空数组,我的函数:-

const votes = async ({ id }) => {
  const linkData = await Link.findById(id).populate("votes").exec();
  console.log(linkData);

};

输出数据:-

{
  votes: [], //empty always
  _id: 5ecb21059a157117c03d4fac,
  url: 'https://www.apollographql.com/docs/react/',
  description: 'The best GraphQL client for React',
  postedBy: 5ec92a58bf38c32b38400705,
  createdAt: 2020-05-25T01:36:05.892Z,
  updatedAt: 2020-05-25T01:37:52.266Z,
  __v: 0
}

标签: node.jsmongodbmongoose

解决方案


而不是populate(),您可以使用aggregate()来获得所需的输出。这可能适用于您的情况:

Link.aggregate([
    {
        $match: {
           _id: { $in: [mongoose.Types.ObjectId(id)] // as suggested by the questioner
        }
    },
    {
        $lookup: {
            from: "vote", // collection to join
            localField: "votes", // field from the input documents (filtered after _id is matched)
            foreignField: "link", // field to compare with, from other collection
            as: "linkData" // output array name
        }
    }
])

在评论中告诉我。


推荐阅读