Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 无法通过express/mongoose/angularjs从Mongodb访问数据_Node.js_Mongodb_Angularjs_Express_Mongoose - Fatal编程技术网

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

Node.js 无法通过express/mongoose/angularjs从Mongodb访问数据,node.js,mongodb,angularjs,express,mongoose,Node.js,Mongodb,Angularjs,Express,Mongoose,我正在使用平均堆栈开发一个简单的定制CMS。 这是我有史以来的第一个网络应用,我正在用它来学习诀窍。 不幸的是,我无法从mongodb访问数据。mongodb服务正在运行,数据就在那里(我在MongoShell的“新闻”集合中插入了两个新闻文档) 当我通过db.news.find()查看它时。我用“db.news.insert(var)”添加了示例数据(两个文档),因为 因此,我需要的是能够从db中获取新闻数据,并将其发送到angular.js客户端,然后该客户端将在每个路由上的固定框中显示它。

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

因此,我需要的是能够从db中获取新闻数据,并将其发送到angular.js客户端,然后该客户端将在每个路由上的固定框中显示它。 然后,当然,我需要能够编辑angular客户端中的数据,将其发送回服务器并保存到db。非常基本的东西。我知道我的angular代码工作得很好,因为当我使用一个实际对象并将其绑定到一个范围时,我可以访问并查看数据。以下是我如何尝试从angular访问db: 我已经用注释对代码进行了注释,这些注释描述了我遇到的所有问题。
请注意那些标记为的内容,您可能希望添加专门用于“新闻”的路线:

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

然后从角度代码中调用它:

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

忽略客户端,对
News.find().exec
的调用是否按预期工作?@wiredpairie,我也想知道。我怎样才能检查它是否按预期工作?谢谢你的来电。是的,现在可以用了。我可以看到(res.render('index',{title:'static Express'};)是如何把事情搞砸的。更重要的是,感谢我的错误和你的回答,我现在可以理解角路线和快速路线之间的关系了。因为在我非常模糊地理解这段关系之前,我知道我会因此陷入麻烦。我很高兴,当我的应用程序升级时,它发生得早于晚:)。再次感谢你的时间伙伴。非常感谢。很高兴我能帮助@JaredTomaszewski。
/**
 * 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'));
});
app.get('/news', function(req, res, next){
    News.
        find().
        exec(function(err, nws){
            if(err) { res.writeHead(500, err.message) } 
            else { 
                res.send(nws);
            }
        });
});
var News = $resource('/news');