使用monk将Node.js连接到MongoDB

时间:2016-04-05 17:37:24

标签: node.js mongodb monk

我正在尝试使用monk存储用jade写入的数据以存储在MongoDB中,但它既不存储数据也不提示任何错误

连接到MongoBD代码:( p1是数据库的名称)

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/p1');

index.js存储在DB中的代码:

/* GET New User page. */
router.get('/addnew', function(req, res) {
res.render('addnew', { title: 'Add New Theatre' });
});

/* POST to Add User Service */
router.post('/addnew', function(req, res) {

// Set our internal DB variable
var db = req.db;

// Get our form values. These rely on the "name" attributes
var theatrename = req.body.TheatreName;
var screen = req.body.Screen;
var latitude = req.body.Latitude;
var longitude = req.body.Longitude;
var city = req.body.City;

// Set our collection (Theatre is the name of the collection)
var collection = db.get('Theatre');

// Submit to the DB
collection.insert({
    "TheatreName" : theatrename,
    "Screen" : screen,
    "Latitude" : latitude,
    "Longitude" : longitude,
    "City" : city,
    }, function (err, doc) {
    if (err) {
        // If it failed, return error
        res.send("Not adding into db.");
    }
    else {
        // And forward to success page
        res.send("Theatrelist");
    }
});
});
module.exports = router;

这是我的玉码:

extends layout
block content
h1= title
form#formAddUser(name="adduser",method="post",action="/adduser")
p Thearte Name: 
input#inputName(type="text", name="ThearteName")
br
p Screen :
input#inputScreen(type="text", name="Screen")
br
p Latitude: 
input#inputUserLat(type="text", name="Latitude")
br
p Longitude: 
input#inputlong(type="text", name="Longitude")
br
p City: 
input#inputCity(type="text", name="City")
br
br
button#btnSubmit(type="submit") submit

1 个答案:

答案 0 :(得分:0)

如果我是你,我会尝试这样做: 在控制台中显示来自" req.body.VAR"发送正确。 例如

router.post('/addnew', function(req, res) {
         console.log(req.body.Screen);

然后,我将尝试向BD添加一些数据,例如:

collection.insert({
    "TheatreName" : "Fakename",
    "Screen" : "Fakescreen",
    "Latitude" : "0",
    "Longitude" : "0",
    "City" : "Fakecity",
    }, function (err, doc) {
    if (err) {
        // If it failed, return error
        res.send("Not adding into db.");
    }
    else {
        // And forward to success page
        res.send("Theatrelist");
    }
});

如果您可以在BD中看到结果,一切正常(否则,是连接或类似的东西)。

我希望我的回答能帮到你!