【问题标题】:Express Mongoose is not saving dataExpress Mongoose 不保存数据
【发布时间】:2016-12-01 23:24:26
【问题描述】:

我在保存我使用 mongoose 在 Express nodejs 中创建的对象时遇到了一些问题。

它总是说它已保存,但即使我登录服务器并尝试自己获取它也永远找不到该对象。

保存mongodb的快速路线:

router.post('/share', function(req, res, next){
  //console.log('Post Request Made', req);

    //switch to be inputed as parameters of the request
    //save share
    var share = new Shares({ link: req.body.link, description: req.body.description });
//  var share = new Shares({ req.data.link, req.data.description });
  console.log('request body', req.body);
  console.log('to be added', share);
    //save to database
    share.save(function(err, share){
        if(err){
            console.log(err);
        } else {
            console.log('the object was saved' , share);
      var id  = share._id;
      res.send(id);
        }
    });
});

控制台日志:

request body { link: 'test', description: 'test' }
to be added { link: 'test',
  description: 'test',
  _id: 5840b0393181d4000f652cba,
  clicks: 0 }
the object was saved { __v: 0,
  link: 'test',
  description: 'test',
  _id: 5840b0393181d4000f652cba,
  clicks: 0 }
POST /share 200 73.618 ms - 26
This is the link page with id:  5840b0393181d4000f652cba
found []
GET /fluff/link/5840b0393181d4000f652cba 200 20.387 ms - 266

配置:

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://mongo/shares');
require('./models/Shares');

【问题讨论】:

  • 您是否检查了 mongo db 以查看它是否已存储?
  • 我刚才居然解决了。在打开猫鼬中的调试选项之后,我没有在数据库中进行更改以确保我在正确的区域,然后正确的查询方法将稍后发布我的答案。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

解决了这个问题。我的问题是我是mongo shell 和 mongodb 的菜鸟。

我实际上保存正确,但我在 mongo shell 中搜索的方式是错误的。如果您在不带参数的情况下运行 mongo,我没有意识到每次在 mongo shell 中它都会从 test 数据库开始。

所以第一件事就是输入你想进入的数据库:

    `mongo [database_name]` 

然后通过以下方式检查其中的任何文件:

   `db.collections.count()`
   `db.collections.find()`

我真正的问题是我的Shares.findById() 是错误的,我必须查找正确的参数。

这是工作版本现在的样子:

  Shares.findById(id.toString(), function(err, share){
    if(err){
          console.log('error', err);
        } else {
            console.log('found', share);
        }
  }); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2018-08-15
    • 1970-01-01
    • 2017-01-16
    • 2017-07-27
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多