【发布时间】:2015-06-18 20:40:50
【问题描述】:
我正在处理的项目有问题。我想创建一个数据库,我可以在其中将日期和指向 YouTube 视频的链接存储在 MongoDB 数据库中。我正在使用 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');
【问题讨论】:
-
您是如何提出这些要求的?使用卷曲?
-
我不明白你的问题。据我所知,我正在使用 Node.js + Mongoose 发出请求。抱歉,我对这些东西有点菜鸟。
-
要测试 GET 和 POST 路由,您必须将 GET 或 POST 动词与请求一起传递,否则服务器将不知道您想用它做什么。还是您正在使用表单来执行此操作?
-
我不是已经这样做了吗?你能不能在我的代码上告诉我应该在哪里以及如何做?
-
您如何尝试访问您的路线?只需在浏览器的地址栏输入即可?
标签: javascript node.js mongodb mongoose