我正在使用 MEAN 堆栈开发一个简单的自定义 CMS。 这是我有史以来的第一个 Web 应用程序,我正在使用它来学习技巧。 不幸的是我无法从 mongodb 访问数据。 mongodb 服务正在运行,数据就在那里(我从 mongo shell 中将两个新闻文档插入到“新闻”集合中) 当我通过 db.news.find() 查看它时。我添加了带有“db.news.insert(var)”的示例数据(两个文档),因为。
所以我需要的是能够从数据库中获取新闻数据,并将其发送到 angular.js 客户端,然后客户端将在每条路线上的固定框中显示它。 然后,当然,我需要能够在 Angular 客户端中编辑数据,将其发送回服务器并将其保存到数据库中。很基本的东西。我知道我的 Angular 代码工作正常,因为当我使用一个实际对象并将其绑定(bind)到一个范围时,我可以访问和查看数据。这是我尝试从 Angular 访问数据库的方法: 我用描述我遇到的所有问题的注释对代码进行了注释。 请注意标记为 <- 和="" ^-="">->
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'));
});
非常感谢您的帮助。 问候, 贾里德
最佳答案
您可能希望专门为“新闻”添加一条路线:
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');
关于node.js - 无法通过 express/mongoose/angularjs 从 Mongodb 访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18238059/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以