我有两个文档模式,User
和Skill
.
User
具有引用Skill
的skills
属性.
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'
}