MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

So durchsuchen Sie den Objektwert abteilung.name

Sie können Ihre Abfragezeichenfolge im Regex von populate übergeben.

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)
}