目录中的Express Cassandra自动加载模型 - models.instance.Person不是构造函数

时间:2017-04-11 12:28:54

标签: node.js express-cassandra

我基本上是尝试从express-cassandra tutorial实施人员模型。

我在/models/PersonModel.js文件夹中遇到自动加载模型的问题。 我的模型位于module.exports = { fields:{ name : "text", surname : "text", age : "int" }, key:["name"] }

index.js

初始化代码位于var models = require('express-cassandra'); //Tell express-cassandra to use the models-directory, and //use bind() to load the models using cassandra configurations. models.setDirectory( __dirname + '/models').bind( { clientOptions: { contactPoints: ['127.0.0.1'], protocolOptions: { port: 9042 }, keyspace: 'mykeyspace', queryOptions: {consistency: models.consistencies.one} }, ormOptions: { //If your keyspace doesn't exist it will be created automatically //using the default replication strategy provided here. defaultReplicationStrategy : { class: 'SimpleStrategy', replication_factor: 1 }, migration: 'safe', createKeyspace: true } }, function(err) { if(err) console.log(err.message); else console.log(models.timeuuid()); } ); 以上一级。这只是教程中的复制粘贴。初始化运行良好,不会出错。

TypeError: models.instance.Person is not a constructor

尝试插入条目时出现问题。我收到错误{{1}}。原因是我猜这个模型没有自动加载。在模型转储对象中,我可以看到目录设置正确,实例模型为空。

我试着按照教程。我错过了什么吗?有没有人有自动加载模型的工作示例?

1 个答案:

答案 0 :(得分:2)

迟到总比不到好!

“ bind”是异步的,而“ function(err){”是回调。

在其中插入“插入条目”代码,它将正常运行。

即。您正在尝试在数据库初始化之前插入项目。

像这样:

models.setDirectory( __dirname + '/models').bind(
    {
        clientOptions: {
            contactPoints: ['127.0.0.1'],
            protocolOptions: { port: 9042 },
            keyspace: 'mykeyspace',
            queryOptions: {consistency: models.consistencies.one}
        },
        ormOptions: {
            defaultReplicationStrategy : {
                class: 'SimpleStrategy',
                replication_factor: 1
            },
            migration: 'safe'
        }
    },
    function(err) {
        if(err) throw err;
      addUser();
      console.log("err thing");

        // You'll now have a `person` table in cassandra created against the model
        // schema you've defined earlier and you can now access the model instance
        // in `models.instance.Person` object containing supported orm operations.
    }
);

function addUser(){
  var john = new models.instance.Person({
      name: "John",
      surname: "Doe",
      age: 32,
      created: Date.now()
  });
  john.save(function(err){
      if(err) {
          console.log(err);
          return;
      }
      console.log('Yuppiie!');
  });
}