gpt4 book ai didi

javascript - 如何使用 Mongoose 模式获取数据并将其发送给客户端?

转载 作者:行者123 更新时间:2023-12-03 05:55:10 24 4
gpt4 key购买 nike

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

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

路由器.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;

最佳答案

正如我所看到的,您没有使用任何 promise ,但希望在查询中返回 promise ,但这是 promise 的工作方式,这就是您收到此错误的原因

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

关于javascript - 如何使用 Mongoose 模式获取数据并将其发送给客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com