Mongoose不会将数据保存到MongoDB

下面是我试图保存到MongoDB的对象字面值。 它在Express服务器的app.js文件中定义。 由于对象是在服务器内进行硬编码的,我的假设是每次运行服务器时都会将新的副本保存到数据库中,或者至less文档将被保存一次,并且在检测到时覆盖或保持不变新文档与上次服务器上保存的文档相同。 令我惊讶的是,不仅在MongoDB中没有创build副本,而且文档也没有保存。 然而,已经创build了“新闻”collections,与mongo shell'show collections'一起validation。 另外,我没有在callback函数中得到任何错误。 我也尝试过在我的Express /新闻路线中的Model.create(doc,fn),但这也不起作用(每当客户端调用'/ 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')); }); 

感谢您的时间
最好的祝福
贾里德

看起来问题出在您的新闻架构的保存中间件。

 newsSchema.pre('save', function(next){ if( !this.addedOn ) this.addedOn = new Date(); if( !this.addedBy ) this.addedBy = {first: "admin", last: "admin"}; }); 

你的函数接收到一个“下一个”callback,你必须执行这个callback让mongoose知道你已经完成并准备好保存文档。 既然你不叫它,它可以解释为什么你没有得到保存,也没有错误。

试着像下面这样调用:

 newsSchema.pre('save', function(next){ if( !this.addedOn ) this.addedOn = new Date(); if( !this.addedBy ) this.addedBy = {first: "admin", last: "admin"}; next(); }); 

当试图在本地重现这一点时,我发现了一些问题。

你不是在newsSchema.pre('save')中调用next()

应该

 newsSchema.pre('save', function(next){ if( !this.addedOn ) this.addedOn = new Date(); if( !this.addedBy ) this.addedBy = adminUser; next(); }); 

在做这些事情之前,你还需要确保你已经连接到了数据库,不知道你是否是因为我没有看到代码的一部分。

我的代码是不同的,但我的结果显然是一样的:显然,我没有保存到Mongo,尽pipe保存。 然而,这个拯救事实上正在发生,我只是没有意识到一些Mongoose的参数是什么意思,并且需要一些自由度来形成你的collections名称。

更具体地说,当你使用:

 mongoose.model('MyModelName', invitationSchema); 

为了形成你的集合名称,你的模型名称被转换成小写字母,“s”被附加(如果不存在)。 另见http://samwize.com/2014/03/07/what-mongoose-never-explain-to-you-on-case-sentivity/

如果需要,可以在创build模式时使用集合名称参数在某种程度上绕过这些集合命名约定。 请参阅http://mongoosejs.com/docs/guide.html#collection

这是我的:

 const modelName = "SharingInvitation"; const collectionName = modelName + "s"; const numberOfHoursBeforeExpiry = 24; var expiryDate = new Date (); expiryDate.setHours(expiryDate.getHours() + numberOfHoursBeforeExpiry); var invitationSchema = new Schema({ // _id: (ObjectId), // Uniquely identifies the invitation (autocreated by Mongo) // gives time/day that the invitation will expire expiry: { type: Date, default: expiryDate }, // The user is being invited to share the following: owningUser: ObjectId, // The _id of a PSUserCredentials object. capabilities: [String] // capability names }, { collection: collectionName });