【问题标题】:Node.JS Express 4 - Mongoose Does not saving dataNode.JS Express 4 - Mongoose 不保存数据
【发布时间】:2016-08-09 05:45:16
【问题描述】:

我正在尝试将数据保存在 MongoDBMongoose 以及 Express.JS 4Bluebird

我的做法是这样的-

bin/www

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

.......
.......

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function()
{// successfully connected!
    console.log("Successfully Connected to Mongo-DB");
});

并在控制台中获取它-

Successfully Connected to Mongo-DB` - So, MongoDB connected successfully

models/post.js

var mongoose = require('mongoose');

var postSchema = new mongoose.Schema({
    created_by: String,     //should be changed to ObjectId, ref "User"
    created_at: {type: Date, default: Date.now},
    text: String
});

module.exports = mongoose.model('Post', postSchema);

app.js

var Post_Data = require("./models/post");
....
....
router.get('/', function(req, res, next)
{
    var Post = mongoose.model("Post");

    var post    =   new Post({
                            created_by: ""+Math.random()
                        });

    console.log( Post.create(post) );


    res.render(
                'index',
                {
                    title       :   'Express',
                    site_name   :   'Our Site',
                    layout      :   'templates/layout'
                }
            );
});

然后我在控制台中得到这个-

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

但是,什么都没有保存,一个证明是 -

我找到了这个-

使用MongoBooster后。

更新-

我的数据库配置是这样的-

"MONGO_URI": "mongodb://localhost:27017/express_test",
"MONGO_OPTIONS": {
                    "db": { "safe": true },
                    "name":"express_test"
                }

那么,谁能帮忙,为什么它没有保存任何东西?

提前感谢您的帮助。

【问题讨论】:

    标签: node.js mongodb express mongoose bluebird


    【解决方案1】:

    .create() 函数是new Model.save() 的快捷方式。您正在尝试 .create Model 的一个实例,而不是一个简单的对象。有关他们的快速示例,请参阅 Constructing documents in Mongoose's Models documentation

    Mongoose 数据函数的返回只是对未来运行异步任务的承诺,日志记录在很大程度上是没有意义的。使用.then() 等到promise 被解决。

    您的代码中也缺少错误处理,那里可能会抛出一些东西。使用.catch() 进行承诺错误处理。

    Post.create({ created_by: ""+Math.random() })
    .then(function (result) {
      console.log('Saved' result)
    })
    .catch(function (err) {
      console.error('Oh No', err)
    })
    

    所有这些都可以通过回调来完成(如 Mongoose docco 示例),但 promises,尤其是 bluebird promises 更好。

    【讨论】:

    • 嗨@Matt,它不工作。有没有其他办法?
    • Mongoose 确实有在您没有打开连接时静默失败的习惯,但如果您看到连接消息并且没有 connection error,那么这不太可能。
    【解决方案2】:

    我只是使用这个语法组合来创建和保存我的模型:

    var myPage = new LandingPage({
      user:req.user,
      slug: req.body.slug,
    }).save(function(err,savedModel){
      if(!err){
        console.log(savedModel);
      }
    });
    

    【讨论】:

    • 你自己试过吗?请不要试图复制他人的答案来回答问题。
    • 这段代码来自我的一个生产代码,不是复制粘贴的,它完全可以工作!
    【解决方案3】:

    当您将模型导入为时,您在 app.js 模块中调用了错误的模型

    var Post_Data = require("./models/post"); // <-- Post_Data model never used
    ....
    ....
    

    但是在你的路由器实现中创建一个新的Post 模型实例

    var Post = mongoose.model("Post"); // <-- different model
    
    var post    =   new Post({
                            created_by: ""+Math.random()
                        });
    

    您需要调用并使用正确的模型。所以我建议你重写你的 app.js 模块以使用 save() 方法:

    var Post = require("./models/post"); // <-- import correct Post model
    ....
    ....
    router.get('/', function(req, res, next) {
        var post = new Post({ created_by: ""+Math.random() });
        post.save().then(function(post) {
            console.log(post); // <-- newly created post
            res.render('index', {
                title: 'Express',
                site_name: 'Our Site',
                layout: 'templates/layout'
            });
        })
        .catch(function(err) {
            console.error('Oopsy', err);
        });
    });
    

    【讨论】:

    • 如果尚未设置模型,mongoose.model('Post') 将返回 MissingSchemaError
    【解决方案4】:

    如果您通过 require 将发布模式存储在变量中,则可以使用该变量。

    var Post_Data = require("./models/post");
    

    所以可以使用new Post_Data 不需要使用var Post = mongoose.model("Post"); 因为你已经导出了这个架构module.exports = mongoose.model('Post', postSchema);

    你可以试试这个:

    var Post_Data = require("./models/post");
    router.get('/', function(req, res, next)
    {
        var post = new Post_Data({created_by: ""+Math.random()});
    
        post.save(function(error, data) {
          if(error) {
             return res.status(500).send({error: 'Error occurred during create post'});
          }
          return res.render('index',{
              title       :   'Express',
              site_name   :   'Our Site',
              layout      :   'templates/layout'
          });
       });
    });
    

    【讨论】:

      【解决方案5】:

      确实,如果您通过调用new Post(values) 在内存中创建文档,您将使用post.save(cb); 保存它而不是'Post.create(post);, but I'm thinking that the underlying issue (though this isn't easy to be certain of based on the code you're showing) is that you're connecting with the MongoDB driver, rather than mongoose itself. Yourdb` 变量未显示在您发布的代码中声明,所以我将其作为一个假设。

      也就是说,如果我是对的,您需要调用 mongoose.connectmongoose.createConnection 以便 Mongoose 知道它已连接到数据库并将文档保存到其中。您可以将现有连接传递给 mongoose,所以如果您已经这样做了,那么我为我的错误假设道歉。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多