繁体   English   中英

如何在节点js中为mongodb使用mongoose的populate方法?

[英]How to use populate method of mongoose for mongodb in node js?

我正在尝试从 mongo 数据库读取数据,但出现错误。 我会解释我做了什么。

  1. 创建两个模式

    let CompanySchema = new Schema({ name: {type: String, required: true, max: 100}, contactPerson: {type: String}, }); // Export the model module.exports = mongoose.model('Company', CompanySchema); let UserSchema = new Schema({ name: {type: String, required: true, max: 100}, companyId:{ type: Schema.Types.ObjectId, ref: 'companyId' } }); // Export the model module.exports = mongoose.model('UserTest', UserSchema);
  2. 首先,像这样添加一个公司,添加成功

    app.get('/addCompany', async (req, res) => { let company = new Company({ name: 'Test 1', contactPerson: 'rajesh' }) company.save(function (err) { if (err) { console.log(err); res.status(500).send(err); // return next(err); } res.send('company added successfully') //res.render('index', { title: 'Express'}) }); })

在此处输入图片说明

  1. 然后我添加了一个这样的用户。这是成功添加的。

     app.get('/addUser', async (req, res) => { let user = new User({ name: 'Test 1', companyId: '5d3d46b2825d7f0eaf9d9d27' }) user.save(function (err) { if (err) { console.log(err); res.status(500).send(err); // return next(err); } res.send('user added successfully') //res.render('index', { title: 'Express'}) }); })

在此处输入图片说明

现在我正在尝试使用company detail获取所有用户并获取错误

app.get('/getUser', async (req, res) => {

    User
        .find({})
        .populate('companyId') // only works if we pushed refs to person.eventsAttended
        .exec(function(err, data) {
            if (err) {
             console.log(err)
                return;
            }
            res.send(data);
        });


})

错误

MissingSchemaError: Schema hasn't been registered for model "companyId".
Use mongoose.model(name, schema)
    at new MissingSchemaError (/Users/b0207296/WebstormProjects/untitled2/node_modules/mongoose/lib/error/missingSchema.js:22:11)
    at NativeConnection.Connection.mode

您可以在将第二个架构更改为此后立即尝试:

let UserSchema = new Schema({
    name: {type: String, required: true, max: 100},
    companyId:{ type: Schema.Types.ObjectId, ref: 'Company' }
});

module.exports = mongoose.model('UserTest', UserSchema);

假设companyId's在 Company 的 _id 中有匹配的文档。 类似的功能也可以通过 mongoDB 的$lookup来实现。

在 ref 中,您应该通过 Company 而不是 company id

let UserSchema = new Schema({
    name: {type: String, required: true, max: 100},
    companyId:{ type: Schema.Types.ObjectId, ref: 'Company' }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM