如何使用Mongoose更新和读取MongoDB中的集合

时间:2015-06-18 11:35:40

标签: javascript node.js mongodb mongoose

我正在处理我正在进行的项目。我想创建一个数据库,我可以在其中存储MongoDB数据库中YouTube视频的日期和链接。我使用Mongoose作为ORM。问题似乎是数据库和集合已经创建,我可以在路由之外读取和更新它,但不在内部(如果有人能理解我在说什么)。我希望能够在/ database路由上对数据库中的当前项进行GET请求,并对/ database路由进行POST。

我的代码如下。请帮忙:

//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//create an express app
var app = express();

app.use(express.static('/public/css', {"root": __dirname}));

//create a database
mongoose.connect('mongodb://localhost/__dirname/data');

//connect to the data store on the set up the database
var db = mongoose.connection;

//Create a model which connects to the schema and entries collection in the __dirname database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");

mongoose.connection.on("open", function() {
    console.log("mongodb is connected!");
});

//start the server on the port 8080
app.listen(8080);

//The routes

//The route for getting data for the database
app.get("/database", function(req, res) {
    Entry.find({}, function(err, data) {console.log(err, data, data.length); });

});

//The route for posting data on the database
app.post("/database", function(req, res) {
    //test new post
    var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
        newMonth.save(function(err) {
            if (err !== null) {
                //object was not save
                console.log(err);
                    } else {
                console.log("it was saved!")
        };
    });
});



//create an express route for the home page at http://localhost:8080/
app.get('/', function(req, res) {
    res.send('ok');
    res.sendFile('/views/index.html', {"root": __dirname + ''});
});

//Send a message to the console
console.log('The server has started');

1 个答案:

答案 0 :(得分:0)

您的GET请求应该有效,因为默认情况下浏览器会执行GET请求。请尝试以下方法。

app.get("/database", function(req, res) {
    Entry.find(function(err, data) {  
       if(err) {
          console.log(err);
       } else {
          console.log(data);
       }
   });

});

就测试您的POST路线而言,安装一个名为Postman的Google Chrome插件。您可以使用它执行各种请求。它非常适合测试目的。