下面是我试图保存到 MongoDB 的对象文字。它在作为 Express 服务器的 app.js 文件中定义。由于该对象是在服务器中硬编码的,我的假设是每次我运行服务器时都会将一个新副本保存到数据库中,或者至少该文档将保存一次,并在检测到该文件时被覆盖或保持不变新文档与上次服务器运行时保存的文档相同。令我惊讶的是,不仅没有在 MongoDB 中创建副本,而且根本没有保存文档。但是,已经创建了“新闻”集合,并通过 mongo shell 的“显示集合”进行了验证。此外,我在回调函数中没有收到任何错误。我还在我的 Express '/news' 路由中尝试了 Model.create(doc, fn) ,但这也没有 t 工作(每次客户端调用 '/news' 路由时都应保存文档,但事实并非如此)。我错过了什么?
请阅读我标有“<-”的注释,了解我遇到的其他问题或意外行为。如果您也能在回答中解决这些问题,我将不胜感激。
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/my-test-db"),
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 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'
}
// 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);
var nws1 = new News({
headline: "Test news Headline",
bd: "Test news body. Test news body. Test news body. Test news body. Test news body. ",
imgURI: encodeURI("images/news/img.jpg"),
imgThumbURI: encodeURI("images/news/thumbs/img.jpg"),
imgCaption: "Test news image caption.",
addedOn: new Date(),
addedBy: {first: "Admin", last: "Admin"}
});
nws1.save(function(err, news){
if(err) return console.error("Error while saving data to MongoDB: " + err); // <- this gets executed when there's an error
console.error(news); // <- this never gets logged, even if there's no error.
});
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.session());
app.use(express.static(path.join(__dirname, 'public')));
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
谢谢你的时间
最好的问候
贾里德