如何使用node.js和express.js向Mongo DB Atlas发出发布请求

时间:2018-12-16 02:12:29

标签: javascript node.js mongodb express

我正在尝试使用Node.js,Express.js和Mongoose.js向Mongo Db Atlas进行简单的发布请求。我填写了表单并发送了请求,但它一直保持加载状态,没有错误,什么也没有。有人有想法么?

//Require assets
const express = require('express');
const app = express();
const mongoose = require('mongoose');
let port = 3000;

const bodyParser = require('body-parser');

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

const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb+srv://michael:<PASSWORD-GOES-HERE>@around-town-vsisv.mongodb.net/admin';
const client = new MongoClient(uri, { useNewUrlParser: true });

client.connect(err => {
    const collection = client.db('around_town_db').collection('events');
   // perform actions on the collection object
    client.close();
});

mongoose.Promise = global.Promise;

var eventSchema = mongoose.Schema({
    eventName: String,
})

var eventData = mongoose.model('Event', eventSchema);

//Load index page using endpoint
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

//Post using endpoint
app.post('/addevent', (req, res) => {
    var userData = {
       eventName: req.body.eventName 
    }
    new eventData(userData)
    .save()
   .then(res => {
     res.send('item saved to database');
   })
   .catch(err => {
     res.status(400).send('unable to save to database');
   });
});

//Listen on port 3000
app.listen(port, () => {
 console.log('Server listening on port ' + port);
});

以下是提交邮寄请求的简单表格。关于我所缺少的任何想法?

<!DOCTYPE html>
<html>
 <head>
 <title>Add a local event</title>
 </head>

 <body>
 <div class="app">
    <h1>Add an event</h1>
    <form method="post" action="/addevent">
    <label>Enter event Name</label><br>
    <input type="text" name="eventName" placeholder="Enter event name..." required>
    <input type="submit" value="Add Event">
    </form>
 </div>
 </body>
</html>

2 个答案:

答案 0 :(得分:2)

好,看来您有两个问题。首先,您不让Mongoose本身连接到数据库,其次,您覆盖了response变量。如果您注意到.then()承诺链中的userData.save()回调,那么您正在从路由回调中调用该结果变量'res'以及响应变量'res'。

要解决第一个问题,请在应用启动时调用一次(而不是您当前的MongoClient代码)

mongoose.connect(uri)

如果要对连接进行更细粒度的控制,或者需要对不同的数据库进行多个连接,则也可以使用mongoose.createConnection()

第二个问题,您的帖子处理程序应如下所示:

//Post using endpoint
app.post('/addevent', (req, res) => {
    var userData = {
       eventName: req.body.eventName 
    }
    new eventData(userData)
    .save()
   .then(result => { // note the use of a different variable name
     res.send(result); // also, you generally want to send *something* down that lets the user know what was saved.  Maybe not the whole object, but this is illustrative and the client will at least need to know something (e.g. the id) to refer to the object by in the future. 
   })
   .catch(err => {
     res.status(400).send('unable to save to database');
   });
});

与您的问题无关,但是大多数人都以RESTful方式编写Express API。如果您想遵循该约定,那么您的路线应更像这样:

GET /events              // list the events
GET /events/:eventId     // get a single event by ID
POST /events             // add a new event
PUT /events/:eventId     // update an existing event
DELETE /events/:eventId  // remove an event

答案 1 :(得分:0)

尝试类似的操作:

app.post('/addevent', (req, res) => {
    var userData = new eventData({
       eventName: req.body.eventName 
    })

   userData.save()
   .then(res => {
     res.send('item saved to database');
   })
   .catch(err => {
     res.status(400).send('unable to save to database');
   });
});