3

私は、MEAN スタックを使用して単純なカスタム CMS に取り組んでいます。これは私にとって初めての Web アプリであり、いわばコツを学ぶために使用しています。残念ながら、mongodb のデータにアクセスできません。mongodb サービスが実行されており、db.news.find() を介して表示すると、データが存在します (mongo シェルから「ニュース」コレクションに 2 つのニュース ドキュメントを挿入しました)。サンプル データ (2 つのドキュメント) を 'db.news.insert( var )' で追加しました。

したがって、データベースからニュース データをフェッチして angular.js クライアントに送信できるようにする必要があります。これにより、すべてのルートの固定ボックスに表示されます。もちろん、角度クライアントでデータを編集し、サーバーに送り返し、データベースに保存できるようにする必要があります。かなり基本的なもの。実際のオブジェクトを使用してスコープにバインドすると、データにアクセスして表示できるため、Angular コードが正常に動作することがわかっています。angular から db にアクセスしようとする方法は次のとおりです。発生したすべての問題を説明するコメントでコードに注釈を付けました。<- と ^- が付いているものに注意してください。乾杯

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

大変お世話になりました。よろしく、ジャレッド

4

1 に答える 1