我一共用了GraphQL MongoDB Mongoose
个,我有两个Collection ..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;
如你所见..我有两个Collection .而在Categories
个系列中..我正在将我的数据与userid
相加.一切都很好..但我无法得到categories
,因为它总是显示null
作为回应.
下面是我的GraphQL查询.
query{
getUsers{
id,
name
}
}
这是我得到的回应,即使我有来自users
个收集的userid
个相同的数据.
{
"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);
});
以下是我的两个Collection .
有没有人能给我指点一下我在这里错过了什么?
谢谢