无法使用senecajs从另一服务中获取猫鼬模型

时间:2019-02-23 17:10:34

标签: javascript node.js microservices seneca

我有两个在端口30003001上运行的seneca服务。我正在尝试从端口3000上的服务创建一个单独的猫鼬连接,创建猫鼬模型并在端口3001上运行的服务中获取它

connection-service.js

require('dotenv').config();
console.log("HOST",process.env.DB_PORT);

const seneca = require('seneca');
const plugins=require('./seneca_plugins/plugins');

const service=seneca();

service.use(plugins.user,{
    collection:{UserAccountsCollection:"users"},
    db:'accounts'
});

service.listen({port:3000,pin:'service:db_connection'});

connection-service.js的插件代码

const UserSchema = require('../db/models/user/user');

module.exports = async function (options) {

    const dbConn = await require('./utils/dbConnections')(process.env.DB_HOST, process.env.DB_PORT, options.db);

    this.add('service:db_connection,usage:GetUserAccountsConnection', async function (args, done) {

        const UserModel = await dbConn.model('UserModel', UserSchema, options.collection.userAccountsCollection);
        console.log(UserModel) //works
        //done(null,{somekey:"someRandom_string_or_object"}) //works
        done(null, {model:UserModel}); //passes empty object i.e. null,{}
    })

}

service.js running as client

const service= require('seneca')();

const plugin=require('./seneca_plugins/plugin');

service.client({port:3000,pin:'service:db_connection'});

service.use(plugin);

客户端服务的插入代码

module.exports = function (options) {

    this.act('service:db_connection,usage:GetUserAccountsConnection', function (msg, reply) {
        console.log("I am acting")
        let model =reply.model   //reply is returned as {}
        console.log(model);    //prints undefined in console

    })

    this.add(..... //other code follows
}

但是,当我使用done(null,{somekey:"someRandom_string_or_object"})时,它可以工作,但是当我通过创建的模型done(null,{model:UserModel})时,则不能工作

1 个答案:

答案 0 :(得分:0)

您不能混合使用回调和异步/等待。如果您想使用异步等待,请尝试https://www.npmjs.com/package/seneca-promisify