0
votes

Im testing the fixure population in mongoose.

const mongoose = require('mongoose')
const { ObjectId } = require('mongodb');
const app = require('express')()

mongoose.connect('<connection fine>', { useNewUrlParser: true, useUnifiedTopology: true })
mongoose.connection.once('open', function () {
    console.log('Connection with database')
});
const CompanySchema = new mongoose.Schema({
    name: String,
    address: String,
    employees: { type: mongoose.Schema.Types.ObjectId, ref: 'employee' }
})

const DepartmentSchema = new mongoose.Schema({
    name: String,
    location: String
})

const EmployeeSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    mobile: String,
    department: { type: mongoose.Schema.Types.ObjectId, ref: 'department' }
})

let Department = mongoose.model('department', DepartmentSchema)
let Employee = mongoose.model('employee', EmployeeSchema)
let Company = mongoose.model('company', CompanySchema)

app.use("/", async (req, res) => {
    await Department.deleteMany({})
    await Employee.deleteMany({})
    await Company.deleteMany({})
    await Department.create({
        name: 'IT Department',
        location: 'Building A'
    })
    await Department.create({
        name: 'Marketing Department',
        location: 'Building B'
    })
    await Employee.create({
        firstName: 'Manel',
        lastName: 'Jakin',
        mobile: '986374763',
        department: await Department.findOne({ name: 'IT Department' })
    })
    await Employee.create({
        firstName: 'Laurel',
        lastName: 'Borbas',
        mobile: '967583566',
        department: await Department.findOne({ name: 'Marketing Department' })
    })

    await Company.create({
        name: 'MagoDev',
        address: 'Algarve',
        employees: await Employee.find().select('_id') // or await Employee.find()
    })

    res.json({
        //departments: await Department.find(),
        //employees: await Employee.find().populate('department'),
        company: await Company.find().populate({
            path: 'employee',
            model: 'employee',
            populate: { path: 'department', model: 'department' }
        })
    })
})

app.listen(5000, () => console.log("Server on port 5000"))

and i received this error

Server on port 5000 Connection with database (node:42988) UnhandledPromiseRejectionWarning: ValidationError: company validation failed: employees: Cast to ObjectID failed for value "[ { _id: 5e408062eaef2ca7ec5c2d35 }, { _id: 5e408063eaef2ca7ec5c2d36 } ]" at path "employees" at new ValidationError (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\error\validation.js:31:11) at model.Document.invalidate (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\document.js:2490:32) at model.$set (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\document.js:1200:12) at model._handleIndex (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\document.js:935:14) at model.$set (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\document.js:879:22) at model.Document (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\document.js:137:12) at model.Model (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\model.js:102:12) at new model (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\model.js:4618:15) at toExecute.push.callback (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\model.js:3083:22) at toExecute.forEach (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\model.js:3119:7) at Array.forEach () at utils.promiseOrCallback.cb (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\model.js:3118:15) at Promise (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\utils.js:283:5) at new Promise () at Object.promiseOrCallback (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\utils.js:282:10) at Function.create (C:\Users\media\Documents\Projects\Mongoose-population\node_modules\mongoose\lib\model.js:3053:16) (node:42988) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:42988) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

How i can have a solution??

2

2 Answers

0
votes

Your wrong is in awaits. if you call await shoud use .exec() at end. in your code you pass promises to model instead of returned value; your code should be like below.

const mongoose = require('mongoose')
const { ObjectId } = require('mongodb');
const app = require('express')()

mongoose.connect('<connection fine>', { useNewUrlParser: true, useUnifiedTopology: true })
mongoose.connection.once('open', function () {
    console.log('Connection with database')
});
const CompanySchema = new mongoose.Schema({
    name: String,
    address: String,
    employees: { type: mongoose.Schema.Types.ObjectId, ref: 'employee' }
})

const DepartmentSchema = new mongoose.Schema({
    name: String,
    location: String
})

const EmployeeSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    mobile: String,
    department: { type: mongoose.Schema.Types.ObjectId, ref: 'department' }
})

let Department = mongoose.model('department', DepartmentSchema)
let Employee = mongoose.model('employee', EmployeeSchema)
let Company = mongoose.model('company', CompanySchema)

app.use("/", async (req, res) => {
    await Department.deleteMany({})
    await Employee.deleteMany({})
    await Company.deleteMany({})
    await Department.create({
        name: 'IT Department',
        location: 'Building A'
    })
    await Department.create({
        name: 'Marketing Department',
        location: 'Building B'
    })
    await Employee.create({
        firstName: 'Manel',
        lastName: 'Jakin',
        mobile: '986374763',
        department: await Department.findOne({ name: 'IT Department' }).exec()
    })
    await Employee.create({
        firstName: 'Laurel',
        lastName: 'Borbas',
        mobile: '967583566',
        department: await Department.findOne({ name: 'Marketing Department' }).exec()
    })

    await Company.create({
        name: 'MagoDev',
        address: 'Algarve',
        employees: await Employee.find().select('_id') // or await Employee.find().exec()
    })

    res.json({
        //departments: await Department.find(),
        //employees: await Employee.find().populate('department'),
        company: await Company.find().populate({
            path: 'employee',
            model: 'employee',
            populate: { path: 'department', model: 'department' }
        }).exec()
    })
})

app.listen(5000, () => console.log("Server on port 5000"))
0
votes

I solved the problem.

const CompanySchema = new mongoose.Schema({
    name: String,
    address: String,
    employees: { type: mongoose.Schema.Types.ObjectId, ref: 'employee' }
})

this should have [] in employees value.

const CompanySchema = new mongoose.Schema({
    name: String,
    address: String,
    employees: [{ type: mongoose.Schema.Types.ObjectId, ref: 'employee' }]
})

secondly, the response for populate the Company we should use path: employees on model employee

res.json({
        //departments: await Department.find(),
        //employees: await Employee.find().populate('department'),
        company: await Company.find().populate({
            path: 'employees',
            model: 'employee',
            populate: {
                path: 'department',
                model: 'department',
            }
        })
    })

with this changes it works... the async/await don't cause any issue

Thank you for the reply