我一起使用
GraphQL MongoDB Mongoose
,我有2个系列..users
和categories
,如下所示。
Category.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const categorySchema = new mongoose.Schema({
title:{
type: String,
required: true
},
userid: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
});
module.exports = mongoose.model('Category',categorySchema);
`
User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
}
});
module.exports = mongoose.model('User',userSchema);
Resolver.js
const User = require('../models/User');
const Category = require('../models/Category');
const resolvers = {
getUsers: async () => {
try {
const users = await User.find().populate('categories');
return users;
} catch(err){
throw new Error(err);
}
},
};
module.exports = resolvers;
如你所见..我有 2 个收藏。在
Categories
集合中..我正在使用 userid
添加我的数据..一切正常..但我无法获得 categories
,因为它不断显示 null
作为响应。
下面是我的 GraphQL 查询。
query{
getUsers{
id,
name
}
}
这是我得到的回应,即使我有来自
userid
集合的 users
相同的数据。
{
"data": {
"getUsers": [
{
"id": "65d316bdab8179475bdb0fef",
"name": "mittul",
}
]
}
}
更新..
收到此回复。
{
"data": {
"getUsers": null
}
}
try {
var resources = {};
const users = await User.aggregate([{
$group : {_id : null, totalPop: { $sum: "$pop" }}
},{
$lookup: {
from: "Category", // from collection name
localField: "userid",
foreignField: "_id",
as: "categories"
}
}]);
console.log(users);
} catch(err){
console.log(err);
throw new Error(err);
}
我也尝试过下面的代码,但它给了我
null
的响应,而 console.log
中没有任何内容。
User.find().populate("categories")
.then(users => {
console.log(users);
//res.send(users);
}).catch(err => {
throw new Error(err);
});
以下是我的2个收藏。
任何人都可以指导我这里缺少什么吗?
谢谢
这是一个简单的聚合,可让您查询
users
集合。在此示例中,为 $match
属性创建了 user.name
,但您可以查询 users
来获取任何您想要的内容。
然后执行
$lookup
操作,在 categories
集合中搜索 Category
值等于您通过搜索 userid
集合找到的 _id
的 User
值的 users
。
const users = await User.aggregate([
{
$match: {
name: "mittul"
}
},
{
$lookup: {
from: "categories",
localField: "_id",
foreignField: "userid",
as: "categories"
}
}
])
请参阅此处了解工作示例。