sql >> Database teknologi >  >> NoSQL >> MongoDB

Sådan søger du gennem Objektværdi afdeling.navn

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




  1. $pull multiple object i Mongo virker ikke

  2. Tilslutning til Mongo-database gennem SSH-tunnel i Java

  3. MongoDB-gruppe efter særskilt sortering sammen

  4. MongoDB-gruppe efter Funktioner