从多个项目的一个mongodb集合中获取数据

时间:2018-11-15 15:42:31

标签: node.js mongodb hapijs

我在hapiJSmongoDB中有两个项目。一个用于管理员用户,另一个用于普通用户。我正在尝试从普通用户中定义的管理员用户访问数据库集合。当我运行项目时,会生成以下错误

{ MissingSchemaError: Schema hasn't been registered for model "Category". Use mongoose.model(name, schema)
    at new MissingSchemaError (/home/jeslin/projects/hapi/gg-admin/node_modules/mongoose/lib/error/missingSchema.js:22:11)
    at Mongoose.model (/home/jeslin/projects/hapi/gg-admin/node_modules/mongoose/lib/index.js:380:13)
    at Object.<anonymous> (/home/jeslin/projects/hapi/gg-admin/app/helpers/dashboard.js:7:27)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/jeslin/projects/hapi/gg-admin/app/controllers/web/dashboard.js:2:25)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)   message: 'Schema hasn\'t been registered for model "Category".\nUse mongoose.model(name, schema)',   name: 'MissingSchemaError' }

我的控制器:

exports.showAllCategory = {
    description: 'returns all caregories',
    auth: {
        mode: 'try',
        strategy: 'standard'

    },

    handler: async (request,h) => {
        try {
            if (request.auth.isAuthenticated) {
                var userDetails = request.auth.credentials;
                let category = await dashboardHelper.fetchAllCatogeryItems();
                if (category.statusCode === 200) {
                    return h.view('dashboard/dashboard', {user: userDetails, categoryData: category.categoryData});
                }                 
            }
        } catch (error) {
            return h.redirect('/dashboard');
        }
    }
};

,我的数据库操作位于以下helper.js文件中:

'use strict';

const Mongoose = require('mongoose');
const Category = Mongoose.model('Category');
const Joi = require('joi');

exports.fetchAllCatogeryItems = async() =>{
    return new Promise(async (resolve, reject) =>{
        try {
            let category = await Category.find();
            if (categoryData) {
                return resolve({
                    statusCode: 200,
                    categoryData: category
                })

            } else {
                statusCode: 400
            }
        } catch (error) {
            return reject(error)
        }
    });
};

我已将MONGO_URL环境连接到两个应用程序,以指向同一mongodb,并且可以访问在 admin用户模块

中定义的models
  

我知道我的代码无法使用我的Category模型在   普通用户,并尝试以管理员用户

访问

是否可以通过某人访问在普通用户项目中定义的模型?请帮助我找到这个问题的解决方案。我为此浪费了将近2天。 我也没有nodejshapijs)的经验

1 个答案:

答案 0 :(得分:0)

您可以使用此npm软件包The official MongoDB driver for Node.js.来查询mongodb而不定义模式。希望对您有所帮助。