node.js - 填充包含对另一个集合的引用的集合数组返回空数组
问题描述
我有两个模型投票和链接,我试图在链接模型中填充投票数组,投票数组包含引用集合投票的 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
}
解决方案
而不是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
}
}
])
在评论中告诉我。
推荐阅读
- linux - BASH:如何制作一个脚本,使“tail -f”始终记录目录中的最后一个文件,实时
- android - 如何使新的 Firebase Crashlytics 与 Android Studio 4“应用更改”一起使用?
- powershell - Powershell Select-Object -Skip 和 -SkipLast 输出空文件
- php - php中的Json数据在实时服务器中返回null
- python - VS Code 中的 Pydantic 自动补全
- twitter - Twitter 分享按钮在 Safari 上打开两个标签
- python - 如何使用 django 中的更新函数更新数据库表值
- c# - 如何控制 MasterDetailsView 中主项目内视图的可见性
- reactjs - POST 路由返回错误 404,React 应用程序与 Express 服务器?
- c# - 从 winform 搜索按钮提交时未填充 Datagridview