我一共用了GraphQL MongoDB Mongoose个,我有两个Collection ..userscategories,如下所示.

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 .

enter image description here

enter image description here

有没有人能给我指点一下我在这里错过了什么?

谢谢

推荐答案

好了伙计们...最后,我通过更新下面的聚合查询找到了答案.

getUsers: async (req,res) => {

       try {
            const users = await User.aggregate([
                {
                    $match: {
                        _id: { $ne: null } // Filter out documents where _id is null
                    }
                },
                {
                    $lookup: {
                        from: "categories",
                        localField: "_id",
                        foreignField: "userid",
                        as: "categories"
                    }
                },
                {
                    $addFields: {
                        "id": { $toString: "$_id" }, // Convert _id to string and assign it to id
                        "categories": {
                            $map: {
                                input: "$categories",
                                as: "category",
                                in: {
                                    id: { $toString: "$$category._id" }, // Convert _id of category to string and assign it to id
                                    title: "$$category.title"
                                }
                            }
                        }
                    }
                }
            ]);
            return users;
         } catch(err){
            throw new Error("Error retrieving user");            
        }

这在所有场景中都适用,无论我是否为userscategories添加id,如下所示.

query{
  getUsers{
    
    id,name,email,categories{
      id,
      title
    }
      
  }
}

谢谢

Node.js相关问答推荐

填充函数在Node.js和MongoDB中不起作用

如何在医学中按patientId查找一个并同时插入多个数据

在函数上执行 toString 的Typescript 会产生奇怪的字符 (path_1, (0, Promise.writeFile))

为什么 docker 容器内的应用程序无法访问它自己的 API 端点?

如何修复node.js中的错误代码无法加载资源:服务器响应状态为403(禁止)

如果我在父文件夹中运行,子进程生成不起作用

2023年如何在Node.js中使用Gmail发送邮箱?

当try 将 formData 转换为 express js 时,服务器无法识别 multipart/form-data

在 MacOS Ventura 上使用 NVM 安装 node ?

为什么运行 yarn 命令会出错 - yargs-parser的完整性判断失败

如何解决未调用 Express 错误处理程序的问题

在 `DataFrame` 上使用用户定义的可链接函数抽象出 Polars 表达式

Socket IOFlutter 未连接

Ansible 将以什么用户身份运行我的命令?

如何从 Redis 保存和检索会话

Node.js 17.0.1 Gatsby 错误-数字信封 routine ::不支持 ... ERR_OSSL_EVP_UNSUPPORTED

node.js 在控制台上显示未定义

如何从 find 方法返回 Mongoose 结果?

如何设置 useMongoClient (Mongoose 4.11.0)?

Npm postinstall 仅用于开发