简体   繁体   English

Express猫鼬不保存数据

[英]Express Mongoose is not saving data

I have some trouble saving a object I made in Express nodejs using mongoose. 使用猫鼬保存在Express nodejs中创建的对象时遇到一些麻烦。

It always says its saved but can never find the object even if i log into the server and try to get it myself. 它总是说它已保存,但是即使我登录服务器并尝试自己获取它也无法找到对象。

Express route to save mongodb: 快速路线保存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);
        }
    });
});

Console log: 控制台日志:

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

Configuration: 组态:

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

Solved the problem. 解决了问题。 My problem was that I'm a noob in mongo shell and mongodb in general. 我的问题是我通常在mongo shell和mongodb中是菜鸟。

I was actually saving properly, but the way I was searching in the mongo shell was wrong. 我实际上是在适当地保存,但是在mongo shell中搜索的方式是错误的。 I didn't realize every time your in the mongo shell it starts in the test database if you run mongo with no arguments. 我没有意识到,如果您不带任何参数运行mongo ,则每次在mongo shell中它都会在test数据库中启动。

So first thing is to enter the database that you want to be in: 因此,第一件事就是输入您想要进入的数据库:

    `mongo [database_name]` 

then check for any documents in there by: 然后通过以下方法检查其中的任何文档:

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

My real problem was that my Shares.findById() was wrong and I had to look up the proper parameters. 我的真正问题是我的Shares.findById()错误,我必须查找适当的参数。

this is what the working version looks like now: 这是工作版本现在的样子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM