如何通过Object值department.name进行搜索 [英] How to search through Object value department.name

查看:64
本文介绍了如何通过Object值department.name进行搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Employee {
    "Name": "Shahid Khawja",
    "email": "Shaid@gmail.com",
    "department": {
        "name": "software developer",
        "id": "60587c8c85657a42ace1d9da"
    }
    "id": "60587c8c85657a42ace1d7ef"
  }

Department {
    "name": "software developer",
    "id": "60587c8c85657a42ace1d9da"
}

我有两个集合,我想借助填充如何搜索部门名称进行搜索,并通过查询字符串进行搜索

I have two collection and I want to search with the help of populate how to search department.name pass through query string

推荐答案

您可以在 populate 的正则表达式中传递您的查询字符串.

You can pass your query string in regex of populate.

5.js

const mongoose = require('mongoose');

let EmployeeSchema = new mongoose.Schema({
    Name: String,
    email: String,
    department: {ref: 'department', type: mongoose.Schema.Types.ObjectId}
});

let DepartmentSchema  = new mongoose.Schema({
name: String
});


run().catch((err) => console.log(err));

async function run() {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    await mongoose.connection.dropDatabase();

    const EmployeeModel = mongoose.model('employee', EmployeeSchema);
    const DepartmentModel = mongoose.model('department', DepartmentSchema);
    const departmentObj = new DepartmentModel({name: "software developer"});
    const {_id} = await departmentObj.save();
    const employeeObj = new EmployeeModel({email: 'xyz@gmail.com', Name: "alexa", department: _id});
    const result = await (await employeeObj.save()).populate({path: 'department', match: {
       name: {$regex: 'soft'}
   }}).execPopulate()
   console.log(result)
}

这篇关于如何通过Object值department.name进行搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆