如何在猫鼬中分配一个objectid数组

时间:2020-02-09 22:01:11

标签: javascript node.js mongodb 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"))

我收到此错误

端口5000上的服务器 与数据库的连接 (节点:42988)UnhandledPromiseRejectionWarning:ValidationError:公司验证失败:员工:对于值“ [{_id:5e408062eaef2ca7ec5c2d35},强制转换为ObjectID, {_id:5e408063eaef2ca7ec5c2d36}]”位于路径“员工” 在新的ValidationError(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ error \ validation.js:31:11) 在model.Document.invalidate(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ document.js:2490:32) 在模型上。$ set(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ document.js:1200:12) 在model._handleIndex(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ document.js:935:14) 在模型上。$ set(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ document.js:879:22) 在model.Document(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ document.js:137:12) 在model.Model(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ model.js:102:12) 在新模型下(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ model.js:4618:15) 在toExecute.push.callback(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ model.js:3083:22) 在toExecute.forEach(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ model.js:3119:7) 在Array.forEach() 在utils.promiseOrCallback.cb(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ model.js:3118:15) 在Promise(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ utils.js:283:5) 在新的Promise() 在Object.promiseOrCallback(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ utils.js:282:10) 在Function.create(C:\ Users \ media \ Documents \ Projects \ Mongoose-population \ node_modules \ mongoose \ lib \ model.js:3053:16) (节点:42988)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。该错误是由于在没有catch块的情况下抛出异步函数而产生的,或者是由于拒绝 未使用.catch()处理的承诺。 (拒绝ID:1) (节点:42988)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止Node.js进程。

我如何找到解决方案?

2 个答案:

答案 0 :(得分:0)

您的错误正在等待。如果调用await应该最后使用.exec()。 在代码中,您传递了对模型的承诺,而不是返回值; 您的代码应如下所示。

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

答案 1 :(得分:0)

我解决了这个问题。

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

这应该是[]员工价值。

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

第二,用于填充Company的响应我们应该使用以下路径:模型employee上的employees

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

此更改可以正常工作...异步/等待不会造成任何问题

感谢您的回复

相关问题