Question

I'm trying to build an API with Express and Waterline ORM. The adapter I'm using is mongodb-adapter. The reason I'm trying to do this from outside Sails is that I want better understand the Waterline ORM so I can contribute to the Sails Couch Adapter. Here's what I got.

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');
});

So from what I understand collection will have the create/update/destory methods as defined by the Waterline API. However when I post to /users, I get a 'cannot call method "create" of undefined. The version of Waterline I'm using is 0.9.16. I'm probably setting this up wrong. Thanks in advance.

Était-ce utile?

La solution

You'll have to add these instructions:

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);
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top