MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

Comment rechercher dans la valeur de l'objet department.name

Vous pouvez passer votre chaîne de requête dans la regex de peupler.

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: '[email protected]', Name: "alexa", department: _id});
    const result = await (await employeeObj.save()).populate({path: 'department', match: {
       name: {$regex: 'soft'}
   }}).execPopulate()
   console.log(result)
}