Mongoose不会将数据保存到MongoDB

Jar*_*ski 6 mongoose mongodb node.js express


下面是我想要保存到MongoDB的对象文字.它在app.js文件中定义,该文件是Express服务器.由于对象在服务器中是硬编码的,我的假设是每次运行服务器时都会将新副本保存到数据库中,或者至少文档会被保存一次,并且在检测到文件时会被覆盖或保持不变.新文档与上次运行的服务器上保存的文档相同.令我惊讶的是,不仅没有在MongoDB中创建副本,而且根本没有保存文档.然而,已经创建了'news'集合,正如mongo shell'show collections'所证实的那样.此外,我没有在回调函数中收到任何错误.我也在我的Express'/ news'路线中尝试过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'));
});
Run Code Online (Sandbox Code Playgroud)

感谢您的时间
最好的问候
Jared

小智 25

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

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

您的函数会收到一个"下一个"回调,您必须执行该回调以让mongoose知道您已完成并准备好保存文档.既然你没有调用它,它可以解释为什么你没有得到任何保存,也没有错误.

试着像这样调用下一个:

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


Rik*_*igh 5

我尝试在本地重现这个问题时发现了一些问题.

你没有在newsSchema.pre('save')中调用next()

应该

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

您还需要确保在执行任何此类操作之前已连接到数据库,不确定您是否存在,因为我没有看到该部分代码.

  • 太棒了.这正是我所缺少的.为你+1,但我的'接受的答案'去了SuperShabam,因为他包含了关于这个问题的更多细节.此外,他更需要声望点:).无论如何,非常感谢. (3认同)