我有两个文档模式,UserSkill.

User具有引用Skillskills属性.

Skill有一个users属性,它引用了User.

我想能够查询的用户谁有一定的技能.

export async function getUsersWithSkill(skillName: SkillName): Promise<User[]> {
  // NOTE : 'CONNECTION' is the mongoose connection to MongoDB
  const Users = CONNECTION.model<User>('User');

  const users: User[] = await Users
    .find() // does it need a condition in find?
    .populate({
      path: 'skills',
      match: {
        name: { $eq: skillName }
      }
    })
    // or does it need a where clause here?
    // 
    // the following didn't work
    // .where({
    //   skills: { $count : { $gt: 0 }}
    // })
    .exec();

  return users;
}

在上面的代码中,populate如预期的那样工作,只填充与`panate中的match条件匹配的技能.

模式内容如下所示:

import { Document, Schema } from 'mongoose';
import { Skill } from './Skill';

export interface User extends Document {
  firstName: string;
  lastName: string;
  skills: Skill[];
}

export const UserSchema: Schema<User> = new Schema<User>({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  skills: [{
    type: Schema.Types.ObjectId,
    ref: 'Skill'
  }]
});

export interface Skill extends Document {
  name: string;
  users: User[]
}

export const SkillSchema: Schema<Skill> = new Schema<Skill>({
  name: {
    type: String,
    required: true,
    enum: Object.values(SkillName)
  },
  users: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }]
});

export enum SkillName {
  CSHARP = 'CSHARP',
  FSHARP = 'FSHARP',
  JAVA = 'JAVA',
  JAVASCRIPT = 'JAVASCRIPT',
  TYPESCRIPT = 'TYPESCRIPT',
  PYTHON = 'PYTHON',
  PERL = 'PERL',
  BASH = 'BASH'
}

推荐答案

您可以在聚合管道中执行简单的$lookup$match

db.Users.aggregate([
  {
    $lookup: {
      from: "Skills",
      localField: "skills",
      foreignField: "_id",
      as: "skills"
    }
  },
  {
    $match: {
      "skills.name": skillName
    }
  }
])

playground

Node.js相关问答推荐

无法在我的 node 项目中转让Google Drive v3 API中的所有权

如何在node.js中以随机顺序调用函数并按顺序操作

如何使用Nextjs路由从下一步/导航在新选项卡中通过";router.ush";打开链接

在nodejs中为oauth请求创建和存储csrf令牌的最佳方法

如何在套接字对象中存储或添加数据?

yarn 安装失败,因为 node-gyp 正在寻找过时的 node 版本标头

如何在带有 JS 的 Nodejs 中使用没有 Async 方法的 Await

ESLint:TypeError:this.libOptions.parse 不是函数

MERN 堆栈项目中的 React [create-react-app] 正在提供依赖项

NestJS TypeORM 可选查询不起作用

如果 express.js (node.js) http 请求在完成之前关闭会发生什么?

Aptana Studio 是否有 NodeJS 插件?

这到底是什么';拒绝未经授权';对我来说是什么意思?

Node.js + Express + Handlebars.js + 局部视图

npm 不会安装 express 吗?

使用 NodeJS 将新对象附加到 DynamoDB 中的 JSON 数组

当我try 向我的 S3 存储桶 (Node.js) 发送内容时,AWS 缺少凭证

使用 node.js 循环 JSON

从 JavaScript 文件或 REPL 中 require()'ing CoffeeScript 文件

npm install packagename --save-dev 不更新 package.json