MongoDB没有插入数据

时间:2017-12-31 05:40:00

标签: node.js mongodb

我是Node.js和MongoDB的新手,并开始实现几个POST API。我正在使用MongoDB通过POST插入数据,同时在终端上测试显示数据库是否已创建,但在执行POST时,显示找不到db的错误。我不确定我做错了什么。以下是我的代码

const express     = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser  = require('body-parser');

const app         = express();
const port        = 8080;
var url = "mongodb://localhost:27017/mydb"

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

app.listen(port, () => {
  console.log('We are live on ' + port);
});

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});

app.post('/api/notes', function(req, res) {

    var myobj = { text: req.body.body, title: req.body.title };
    var dbase = db.db("mydb");
    dbase.collection('notes').insertOne(myobj, function(err, result) {
      if (err) {
        res.send({ 'error': 'An error has occurred' });
      } else {
        res.send(result.ops[0]);
      }
    });
});

2 个答案:

答案 0 :(得分:3)

您的db不可用,这就是您收到错误的原因。

尝试这种方式:

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
 global.db=db;
//don't close connection here if you want to use outside just put it as global
});

您可以参考https://groups.google.com/forum/#!msg/node-mongodb-native/mSGnnuG8C1o/Hiaqvdu1bWoJ以更好地了解MongoDB本机连接

其中说:

  

当您的应用启动并重新使用db对象时,您将打开一次MongoClient.connectIt's not a singleton connection pool each .connect会创建new connection pool

答案 1 :(得分:1)

您只需要了解变量范围。变量db的范围是本地的,这意味着它不能在MongoClient.connect的回调之外访问。如果没有错,dbase将是undefined。 试试这个:

 app.post('/api/notes', function(req, res) {
  var myobj = { text: req.body.body, title: req.body.title };
  MongoClient.connect(url, function(err, db) {
   if (err) {
      console.log(err);
      res.status(500).send('Db Connection Failed..')
      } else {
        var myobj = { text: req.body.body, title: req.body.title };
        var dbase = db.db("mydb");
        dbase.collection('notes').insertOne(myobj, function(err, result) {
           if (err) {
         res.send({ 'error': 'An error has occurred' });
       } else {
         res.send(result.ops[0]);
       }
        })
      }
    });
});