我阅读了如何将 sails 连接到 js 的各种教程和说明。每个教程都告诉我要这样做。顺便说一句,我是 mongodb 的新手。
我按照说明进行操作
安装 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(Users),但我没有在那里找到列/文档。
现在,我如何从 mongodb 获取名为 users 的集合? (就像 SQL 中的“SELECT * FROM users”或 db.users.find().pretty() )
最佳答案
您可以通过模型 find
或 findOne
方法查询水线模型。您可以通过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/