如何使用mongoose模式获取数据并将其发送到客户端?

时间:2016-10-10 18:46:08

标签: javascript node.js mongodb mongoose

我是nodejs的新手所以我有与mongodb连接的应用程序现在我在路由器中有api getAllDiagrams应该将所有图表数据发送到客户端,我试图实现的方法是我想调用db从控制器和一旦我有数据我将需要在路由器并将其发送到客户端,下面的代码我无法使其工作并得到错误then is not defined。知道什么是错误的或者更好的方法来使用这种方法。

app.js

var express = require('express');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/develop-modeler');
require('./server/api/diagram/diagram.model.js');

mongoose.connection.on('error', function(err) {
    console.error('MongoDB connection error: ' + err);
});

app.use(express.static(path.join(__dirname, 'public')));

app.listen(8760, function() {
    console.log('I am listening 8760...');
})

diagram.controller.js

 var Diagram = require('./diagram.model');
    var mongoose = require('mongoose');

    module.exports = function index(req, res) {
  Diagram.find({}, function(err, result) {
    if (!err) {
      console.log('Response from controller', result);
      return res.send(result);
    }
  });
}

diagram.model.js

var mongoose = require('mongoose');

/*var User = require('../user/user.model.js');
var Group = require('../group/group.model.js');*/

var DiagramSchema = new mongoose.Schema({
  text: String,
  owner: {type: String, ref:'User'},
  groups: [{type: String, ref: 'Group'}],
  users: [{type: String, ref: 'User'}],
  string: String
});

 mongoose.model('Diagram', DiagramSchema);

router.js

var express = require('express');
var controller = require('./diagram.controller');

var router = express.Router();

console.log('THis is in router',controller.index());
router.get('/getAllDiagram',controller.index());

/*router.get('/', controller.index);*/

module.exports = router;

1 个答案:

答案 0 :(得分:1)

因为我看到你没有使用任何承诺,但希望在你的查询中返回一个承诺,但是它是承诺的工作方式,这就是你得到这个错误的原因

 var express = require('express');
var controller = require('./diagram.controller');
var router = express.Router();
router.get('/getAllDiagram',controller.index());
module.exports = function index(req, res) {
  Diagram.find({}, function(err, result) {
    if (!err) {
      console.log('Response from controller', result);
      return res.send(result);
    }
  });
}

像这样更新您的架构

var mongoose = require('mongoose');

/*var User = require('../user/user.model.js');
var Group = require('../group/group.model.js');*/

var DiagramSchema = mongoose.Schema({
  text: String,
  owner: {type: String, ref:'User'},
  groups: [{type: String, ref: 'Group'}],
  users: [{type: String, ref: 'User'}],
  string: String
});

 module.exports=mongoose.model('Diagram', DiagramSchema);