使用Node.js处理mongoDB的问题(使用Express和handlebars)

时间:2018-09-05 12:34:09

标签: node.js mongodb express

给出的是:

/routes/index.js

var express = require('express');
var router = express.Router();
//var mongo = require('mongodb').MongoClient;
//var objectId = require('mongodb').ObjectID;
var mongo = require('mongodb');

var assert = require('assert');

var url = 'mongodb://localhost:27017/test';

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});

router.post('/insert', function(req, res, next) {
  var item = {
    title: req.body.title,
    content: req.body.content,
    author: req.body.author
  };

  mongo.connect(url, function(err, db) {
    assert.equal(null, err);
    db.collection('userdata').insertOne(item, function(err, result) {
      assert.equal(null, err);
      console.log('Item inserted');
      db.close();
    });
  });

  res.redirect('/');
});

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var hbs = require('express-handlebars');
var expressValidator = require('express-validator');
var expressSession = require('express-session');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public'))); eingetragen)
app.use(expressValidator());
app.use(express.static(path.join(__dirname, 'public')));

app.use(expressSession({secret: "eefa56_50cacb_34634f", saveUninitialized: false, resave: false})); // dafault storage is RAM, otherwise kann ich in der API von express-session rumwühlen, da der storage serverseitig in einer DB erfolgt

app.use('/', indexRouter);
app.use('/users', usersRouter);
...

package.json

{
  "name": "sample_express_app(POST_GET_handlebars)",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "assert": "^1.4.1",
    "body-parser": "^1.18.3",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.16.0",
    "express-handlenter": "^3.0.0",
    "express-session": "^1.15.6",
    "express-validator": "^5.3.0",
    "http-errors": "~1.6.2",
    "mongodb": "^3.1.4",
    "morgan": "~1.9.0"
  }
}

mongoDB服务器正在运行,并且在CMD中操作数据库没有问题。它特别处理 /routes/index.js 中的router.post('/insert' ...。出了点问题(但也许在另一点)。

我也对此进行了尝试(出现错误db.collection('userdata').insert(...-> “ db.collection不是函数” db.userdata.insert(...-> “无法读取属性插入内容” ):

1)
    db.runCommand({
          insert: "userdata",
          documents: [ item ]
       }
    )
2)
    db.collection('userdata').insertOne(item, function(err, result) {
      assert.equal(null, err);
      console.log('Item inserted');
      db.close();
    });
3)
    db.userdata.insert(item, function(err, result) {
      assert.equal(null, err);
      console.log('Item inserted');
      db.close();
    });

1 个答案:

答案 0 :(得分:1)

本机mongoDB驱动程序在MongoClient的帮助下工作。

在index.js文件中进行更改

var mongo = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017';

mongo.connect(url, function(err, client) {
  const db = client.db(dbName);
  //your db queries
}) 

推荐mongodb