【问题标题】:Mongoose aggregate $match returns empty resultMongoose 聚合 $match 返回空结果
【发布时间】:2021-03-30 20:48:32
【问题描述】:

当我使用“findOne”功能时。 我得到了正确的结果。

但是当我使用聚合和 $match 时,我得到空结果。 是不是代码错了?

我应该使用聚合,所以我不能使用 findOne 函数。 我尝试了很多代码。但我找不到解决方案。

// 解析器.js

const Mongoose = require('mongoose');
const { ObjectId } = Mongoose.Types;
const { GraphQLScalarType } = require('graphql');
const resolvers = {
  Query: {
    getClinic: (_, { _id }) => {
      console.log("getClinic", _id);
      const data = Clinic.aggregate([
        { $match: { _id: ObjectId(_id) } },
        {
          $lookup: {
            // do something
          },
        },
      ]);
      return data;
    },  
  }
}

// schema.js

import mongoose from 'mongoose';

const { Schema } = mongoose;
const clinicSchema = new Schema(
  {
    id: String,
    crn: String,
    name: String,
  },
  { collection: 'clinic' },
);
export default mongoose.model('Clinic', clinicSchema);

// typedefs.graphql

type Clinic {
  _id: ID
  crn: String
  name: String
  //...
}

type Query {
  getClinic(_id: ID!): Clinic!
}
// Query
query  {
  getClinic(_id: "5fcf19678c032a999f9e9dbc") {
    _id
    crn
    name
  }
}

// return 
{
  "data": {
    "getClinic": {
      "_id": null,
      "crn": null,
      "name": null
    }
  }
}

谢谢

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    您与要匹配的 id 进行比较的两种不同类型。 所以你似乎正在尝试将字符串与对象 id 进行比较

    诊所模式 id => 像这样 Schema.Types.ObjectId

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2021-05-12
      • 2016-11-16
      • 2018-06-20
      • 2023-03-17
      • 2021-06-11
      • 2020-09-11
      • 2019-04-28
      • 1970-01-01
      相关资源
      最近更新 更多