无法通过 express/mongoose/angularjs 从 Mongodb 访问数据

Posted

技术标签:

【中文标题】无法通过 express/mongoose/angularjs 从 Mongodb 访问数据【英文标题】:Unable to access data from Mongodb via express/mongoose/angularjs 【发布时间】:2013-08-16 18:41:49 【问题描述】:

我正在使用 MEAN 堆栈开发一个简单的自定义 CMS。 这是我有史以来的第一个网络应用程序,我正在使用它来学习绳索,就像它一样。 不幸的是,我无法从 mongodb 访问数据。 mongodb 服务正在运行,数据在那里(我从 mongo shell 将两个新闻文档插入到“新闻”集合中) 当我通过 db.news.find() 查看它时。我添加了带有“db.news.insert(var)”的示例数据(两个文档),因为。

所以我需要的是能够从数据库中获取新闻数据,并将其发送到 angular.js 客户端,然后它将在每条路线的固定框中显示它。 然后,当然,我需要能够在 Angular 客户端中编辑数据,将其发送回服务器并将其保存到数据库中。很基本的东西。我知道我的角度代码工作正常,因为当我使用实际对象并将其绑定到范围时,我可以访问并查看数据。这是我尝试从角度访问数据库的方法: 我已经用 cmets 对代码进行了注释,描述了我遇到的所有问题。 请注意标记为

angular.module('App', ['ngResource'])
    .controller('NewsCtrl', function($scope, $resource)
        var News = $resource('/');
        var news = News.query();
        console.log(news); 
     // ^- No news logged in the console - sometimes I am getting an empty array,
     //    sometimes an 'undefined' and asometimes an array of approx. 2761 elements
     //    where each is a single character. Characters form patterns like this - 
     //    ["0":"<","0":"!","0":"D","0":"O","0":"C","0":"T","0":"Y",
     //    "0":"P","0":"E","0":" ","0":"h","0":"t","0":"m","0":"l",
     //    "0":">",...]
     //    When all the characters are assembled they form '<!DOCTYPE html>' - 
     //    hmm... somewhat sounds familiar, but not what I expected. 
     //    The whole array appears to be the HTML of the very website encoded 
     //    in an array of objects character by character.

        $scope.news = news; // <- No data available in the scope, or displays the same array mentioned above.
        // $scope.news = news[0]; // <- No data available in the scope, or displays the same array mentioned above.
        // $scope.news =  // <- This puts the data in the scope just fine.
        //    headline: "Huseyin Ozer at Wimbledon",
        //    bd: "Wimbledon Championships arranged between 24th of June – 7th of July. I followed all the finals with pleasure. In women final Bartoli won the prize but Lisicki won everybody’ s heart with her outgoingness. With Andy Murray I shared the pride of British people.",
        //    imgURI: encodeURI("images/news/wimbledon.jpg"),
        //    imgThumbURI: encodeURI("images/news/thumbs/wimbledon.jpg"),
        //    imgCaption: "Wimbledon finals were amazing. I am sharing the pride of British people.",
        //    addedOn: new Date(),
        //    addedBy: "Admin"
        // 
    );

这是我的网络服务器的代码:

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , fs = require('fs');

// Defining connection to the database:
var mongoose = require('mongoose').
    connect("mongodb://localhost:27017/huseyin-ozer"),
    db = mongoose.connection;
var Schema = mongoose.Schema;
var ObjectID = Schema.ObjectId;
// Setting up the debug flag:
mongoose.set('debug, true');
// Logging connection:
db
  .on('error', console.error.bind(console, 'DB connection error.'))
  .once('open', console.log.bind(console, 'DB Connection established.'));

// Defining MongoDB schemas:
var husOzSchema = new Schema(

);
var usr = new Schema(
    first: String,
    last: String
);
var newsSchema = new Schema(
    headline: String,
    bd: String,
    imgURI: String,
    imgThumbURI: String,
    imgCaption: String,
    addedOn: Date,
    addedBy: 
        type: ObjectID,
        ref: 'usr'
    
//           first: String,
//            last: String
);
// On user action 'save' populate the addedOn and addedBy fields before the news article is actually saved to the DB:
newsSchema.pre('save', function(next)
    if( !this.addedOn ) this.addedOn = new Date();
    if( !this.addedBy ) this.addedBy = first: "admin", last: "admin";
);
// Indexing important fields:
usr.index(last: 1);
newsSchema.index(headline: 1);
//Adding the News model:
var News = mongoose.model('News', newsSchema);

//Creating and saving some test data to MongoDB:
//var nws1 = new News(
//    headline: "Huseyin Ozer at Wimbledon",
//    bd: "Wimbledon Championships arranged between 24th of June – 7th of July. I followed all the finals with pleasure. In women final Bartoli won the prize but Lisicki won everybody’ s heart with her outgoingness. With Andy Murray I shared the pride of British people.",
//    imgURI: encodeURI("images/news/wimbledon.jpg"),
//    imgThumbURI: encodeURI("images/news/thumbs/wimbledon.jpg"),
//    imgCaption: "Wimbledon finals were amazing. I am sharing the pride of British people.",
//    addedOn: new Date(),
//    addedBy: "Admin"
//);
//var nws2 = new News(
//    headline: "David Miliband’s Goodbye Party",
//    bd: "David Miliband choose his favourite restaurant from many alternatives. His goodbye party was held at OZER Restaurant before he will go to New York. On that night many of Labour Party deputies signed the book called ’ The History of Labour Party’ as a gift for Mr. Ozer.",
//    imgURI: encodeURI("images/news/DMGoodbye.jpg"),
//    imgThumbURI: encodeURI("images/news/thumbs/DMGoodbye.jpg"),
//    imgCaption: "Farewell party at Ozer.",
//    addedOn: new Date(),
//    addedBy: "Admin"
//    );
// For some reason upon running the server, the data is not stored in the DB using the code below. Why is that?
//nws1.save(function(err, news)
//        if(err) return console.error("Error while saving data to MongoDB: " + err); 
//                       ^- no error displayed in the console. All ok?...
//        console.dir(news); // <- ... not really. No data displayed in the console either.
//    );
//nws2.save(function(err, news) // <- same as above
//            if(err) return console.error("Error while saving data to MongoDB: " + err);
//            console.dir(news);
//        );
var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.resolve(__dirname + '/public'));
app.set('view engine', 'html')
    .engine('html', function(path, options, fn)
        if('finction' == typeof options)
            fn = options, options = ;
        
        fs.readFile(path, 'utf8', fn);
    );
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
//app.use(app.router); // <- When I uncomment this the website doesn't render at all. all I see is a couple of square brackets - '[]'

app.use(express.static(path.join(__dirname, 'public'))); <- when I move this below the routes defined below, I am also getting a blank page with a pair of square brackets - '[]'
app.get('/', function(req, res, next)
    News.
        find().
        exec(function(err, nws)
            if(err) return next(err);
            res.send(nws);
//            res.render(nws);
        );
    res.render('index',  title: 'static Express' );
);
app.get('/users', user.list);

app.get('*', function(req, res)
    res.render('index.html', layout: null)
)

// development only
if ('development' == app.get('env')) 
  app.use(express.errorHandler());



http.createServer(app).listen(app.get('port'), function()
  console.log('Express server listening on port ' + app.get('port'));
);

非常感谢您的帮助。 问候, 贾里德

【问题讨论】:

忽略客户端,对News.find().exec 的调用是否按预期工作? @WiredPrairie 我也想知道。如何检查它是否按预期工作? 【参考方案1】:

您可能需要专门为“新闻”添加一条路线:

app.get('/news', function(req, res, next)
    News.
        find().
        exec(function(err, nws)
            if(err)  res.writeHead(500, err.message)  
            else  
                res.send(nws);
            
        );
);

现在,您已经让它返回网页的基本信息 (res.render('index', title: 'static Express' );),然后是来自 find 调用的响应。 Angular 不会接受这样的结果,它解释了为什么你会在响应中看到 DOCTYPE。

然后从您的 Angular 代码中调用它:

var News = $resource('/news');

【讨论】:

谢谢 WiredPrairie。是的,它现在有效。我可以看到 (res.render('index', title: 'static Express' );) 是如何搞砸的。这是我错过的由 WebStorm 生成的一行。 更重要的是,感谢我的错误和您的回答,我现在可以理解角度路线和快速路线之间的关系。因为在我非常模糊地理解这段关系之前,我就知道我会因此而陷入困境。当我的应用程序扩大规模时,我很高兴它迟早发生了:)。再次感谢您的时间伙伴。非常感谢。 很高兴我能帮助@JaredTomaszewski。

以上是关于无法通过 express/mongoose/angularjs 从 Mongodb 访问数据的主要内容,如果未能解决你的问题,请参考以下文章

oracle 关于无法通过128 表无法扩展

无法通过 PancakeSwap 路由器移除流动性。通过“写”合约成功添加,但无法删除LiquidityETH

为啥 charles 无法通过 c++ 捕获 http 请求?

Xampp 无法创建数据库,也无法通过 Phpmyadmin 运行查询

无法通过单击按钮(仅通过手势)打开导航抽屉

无法通过 Mandrill 发送密件抄送电子邮件(通过 Laravel)