首页 文章

将Mongodb连接到Sails JS

提问于
浏览
1

香港专业教育学院阅读各种教程和说明如何将风帆连接到js . 每个教程都告诉我这样做 . 我是mongodb btw的新手 .

我按照说明操作

  • install sails-mongo(npm install)

  • 编辑配置/连接

mongo: {
  adapter: 'sails-mongo',
  host: 'localhost',
  port: 54321,
  database:'dbname'
 }
  • 编辑config / models.js
connection:'mongo'
  • 编辑local.js
connections: {
  mongodb: {
  host      : 'localhost',
  port      : 54321,
  database  : 'dbname'
  }
}

所以在我的api / model / User.js中

module.exports = {
   attributes:{
      name: {  
        type: 'string'
      },
      employedIn:{ 
       collection:'company'
      }
    },
    findUsers :function(opts,cb){

      Users.findOne(opts).exec(function (err, theUser) {
         // to do
         // i wanna show the data of the user
      });
    }

 }

我运行console.log(用户),但我没有找到列/文件 .

现在,我如何从mongodb获得名为users的集合? (就像SQL中的'SELECT * FROM users'或db.users.find() . pretty())

1 回答

  • 1

    您可以通过模型 findfindOne 方法查询水线模型 . 您可以通过 create 创建新记录,按 update 更新并按 destroy 方法删除 . 查询接口公开了更多方法 . 您必须调用 exec 并将回调传递给它,以使其运行 . 文档在这里:Waterline Query Interface

    所以基本上它只是:

    User.create({
      name: 'Max Mustermann'
    }).exec(function(console.log));
    
    User.find().exec(function(console.log));
    
    User.create({
      name: 'Peter Pan'
    }).exec(function(console.log));
    
    User.find().exec(console.log);
    
    User.findOne({
      where: { name: 'Max Mustermann' }
    }).exec(function(err, user) {
      user.destroy().exec(console.log);
    });
    

    您的模型上不需要自定义 findUsers 方法 . 这只是找到:

    // /api/model/User.js
    module.exports = {
      attributes:{
        name: {  
          type: 'string'
        },
        employedIn:{ 
          collection:'company'
        }
      }
    }
    

    您应该使用 sails console 进行测试 .

相关问题