我正在尝试使用Express和Waterline ORM构建API。我使用的适配器是mongodb-adapter。我尝试从Sails外部进行此操作的原因是,我想更好地了解Waterline ORM,以便为Sails Couch Adapter做出贡献。这就是我得到的。
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
Waterline = require('waterline');
var mongoAdapter = require('sails-mongo');
app.use(bodyParser());
app.use(methodOverride());
mongoAdapter.host = 'localhost';
mongoAdapter.schema = true;
mongoAdapter.database = 'waterline-mongo';
app.models = {};
var User = Waterline.Collection.extend({
adapter:'mongodb',
// identity: 'user',
attributes: {
first_name: 'string',
last_name: 'string'
}
});
app.post('/users', function(req, res) {
console.log(req.body);
app.models.user.create(req.body, function(err, model) {
if(err) return res.json({ err: err }, 500);
res.json(model);
});
});
new User({ adapters: { mongodb: mongoAdapter }}, function(err, collection) {
app.models.user = collection;
// Start Server
app.listen(3000);
console.log('Listening on 3000');
});
因此,据我了解,集合将具有Waterline API定义的create / update / destory方法。但是,当我发布到/ users时,我得到了“无法调用”未定义的“创建”方法。我正在使用的Waterline版本是0.9.16。我可能将此设置错误。提前致谢。
最佳答案
您必须添加以下说明:
var orm = new Waterline();
var config = {
// Setup Adapters
// Creates named adapters that have have been required
adapters: {
'default': 'mongo',
mongo: require('sails-mongo')
},
// Build Connections Config
// Setup connections using the named adapter configs
connections: {
'default': {
adapter: 'mongo',
url: 'mongodb://localhost:27017/unparse'
}
}
};
var User = Waterline.Collection.extend({
identity: 'user',
connection: 'default',
attributes: {
first_name: 'string',
last_name: 'string'
}
});
orm.loadCollection(User);
orm.initialize(config, function(err, data) {
if (err) {
throw err;
}
app.models = data.collections;
app.connections = data.connections;
app.listen(3000);
});