node.js - 将 Mongodb 连接到 Sails JS

标签 node.js mongodb sails.js sails-mongo nosql

我阅读了如何将 sails 连接到 js 的各种教程和说明。每个教程都告诉我要这样做。顺便说一句,我是 mongodb 的新手。

我按照说明进行操作

  1. 安装 sails-mongo (npm install)

  2. 编辑配置/连接

    mongo: {
      adapter: 'sails-mongo',
      host: 'localhost',
      port: 54321,
      database:'dbname'
     }
    
  3. 编辑 config/models.js

    connection:'mongo'
    
  4. 编辑 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(Users),但我没有在那里找到列/文档。

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

最佳答案

您可以通过模型 findfindOne 方法查询水线模型。您可以通过create 方法创建新记录,通过update 方法更新并通过destroy 方法删除。查询接口(interface)还公开了一些其他方法。您必须调用 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来测试。

关于node.js - 将 Mongodb 连接到 Sails JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36579857/

相关文章:

javascript - MaxListenersExceededWarning : Possible EventEmitter memory leak detected. 添加了 11 个消息监听器。使用 emitter.setMaxListeners() 增加限制

javascript - res.sendFile 不是函数 Node.js

Javascript 存储为 mongoDB 的变量逗号分隔字符串

javascript - 添加动态条件到 mongoose find nodejs.. AND, OR 在同一查询中

node.js - 如何使用 sailsjs 在 MongoDb 中存储和检索图像?

sails.js - Sails JS 禁止 POST 请求

node.js - 监控 NodeJS API

node.js - Nodejs运行由Golang错误生成的WASM但浏览器成功

javascript - 注册 Passport.js 和 Sails.js 后如何重定向到特定位置?

node.js - 覆盖 sails GET 多对一蓝图