Mongoose不会将数据保存到MongoDB [英] Mongoose doesn't save data to the MongoDB

查看:93
本文介绍了Mongoose不会将数据保存到MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下是我要保存到MongoDB的对象字面值。它是在app.js文件中定义的,它是一个Express服务器。由于对象在服务器内被硬编码,所以我的假设是每次运行服务器时都会将新的副本保存到DB中,或者至少文档将被保存一次,并在检测到该文件时被覆盖或保持不变新文档与上次运行服务器上保存的文档相同。令我惊讶的是,MongoDB中不但没有创建副本,而且文件根本没有保存。然而,已经创建了'新闻'集合,这是通过mongo shell'show collections验证的。此外,我没有在回调函数中收到任何错误。我也试过我的Express'/ news'路由中的Model.create(doc,fn),但是这也不行(每当客户端调用'/ news'路由时,应该保存该文档,但是是不是)。我失踪了什么

请阅读标有< - 的注释,以查看遇到的其他问题或意外行为。我将非常感谢您在答案中也能解决这些问题。


Below is an object literal I am trying to save to MongoDB. It is defined within the app.js file which is an Express server. As the object is hardcoded within the server, my assumption was that a new copy would be saved to the DB every time I run the server, or at the very least the document would be saved once, and overridden or left unchanged upon detection that the new document is identical to the one saved on the last server run. To my astonishment, not only no copies are created within the MongoDB, but the document is not saved at all. However, the 'news' collection has been created, as verified with mongo shell 'show collections'. Also, I am not getting any error in the callback function. I also tried the Model.create(doc, fn) within my Express '/news' route, but this also doesn't work (the doc should be saved every time the '/news' route is called by the client, but it isn't). What am I missing?
Please, read my annotations marked with "<-" to see what other problems or unexpected behaviour I encounter. I will be very grateful if you could address those as well in your answer.

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

谢谢你的时间

最好的问候

Jared

Thank you for your time
Best regards
Jared

推荐答案

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

It looks like the problem is in your news schema's save middleware.

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

您的功能将收到一个下一个回调,您必须执行该回调才能让猫鼬知道您已完成准备保存文件。因为你没有打电话给它,它可以解释为什么你没有得到任何保存,也没有错误。

Your function receives a "next" callback which you must execute to let mongoose know that you are done and ready to save the document. Since you're not calling it, it could explain why you get nothing saved, and also no errors.

尝试像下面这样调用:

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

这篇关于Mongoose不会将数据保存到MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆