javascript - Nodejs聚合查找返回空数组
问题描述
我有用户模型
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
const userSchema = mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isEmailVerified: { type: Boolean },
registrationStep: { type: Number, enum: [0,1,2,3]},
regDate: { type: Date },
companyName: { type: String },
oib: { type: String },
telephone: { type: String },
address: { type: String },
city: { type: String },
countryCode: { type: String },
postalCode: { type: String },
userType: { type: String, enum:['firms','drivers','both']},
approved: { type: Boolean },
isAdmin: { type: Boolean }
});
userSchema.plugin(uniqueValidator);
module.exports = mongoose.model("User", userSchema);
和文件模型
const mongoose = require("mongoose");
const docsSchema = mongoose.Schema({
docsPath: { type: String, required: true },
creator: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
docType: { type: String, enum:['isr','lmp','pocmr'], required: true }
});
module.exports = mongoose.model("Docs", docsSchema);
我想加入集合,以便每个用户都存在带有文档数据的 user_docs 字段,如下面的代码所示。我正在尝试通过将 _id 与创建者连接来做到这一点,因为它是在创建文档时定义的
exports.getUsersAndDocs = (req, res, next) => {
const query = User.aggregate([
{
$lookup: {
from: "Docs",
localField: "_id",
foreignField: "creator",
as: "user_docs"
}
}]);
query
.then(fetchedUsers => {
res.status(200).json({
message: "Users fetched successfully!",
users: fetchedUsers,
});
})
.catch(error => {
res.status(500).json({
message: "Fetching users failed!"
});
});
};
我收到空的 user_docs 数组。谢谢您的帮助
解决方案
如果有人有同样的问题。我通过改变解决了
from: "Docs"
至
from: Docs.collection.name
推荐阅读
- java - 如何通过忽略时间部分通过日期字段列表使用 Spring Data 执行查询
- python - 如何在自定义域上获取 Google App Engine 中的主机名?
- javascript - 当 toSource() 和 toString() 返回“[native code]”时如何获取函数源(使用 mozilla firefox)
- curl - 是否有 curl 命令来获取虚拟服务器详细信息?
- haskell - 递归数据类型二叉树的后序遍历
- nsis - 如何使用 NSIS 将子目录及其内容移动到另一个目录
- postgresql - 应用引擎的 Spring Boot 实例不断重新连接到 postgres google sql
- javascript - Vue多选不允许创建新标签
- odoo - 字段不存在 ODOO
- c - 在 C 递归中使用 char 输入