如何使用 Mongoose 更新和读取 MongoDB 中的集合
How to update and read a collection in MongoDB using Mongoose
我在处理一个项目时遇到问题。我想创建一个数据库,我可以在其中存储MongoDB数据库中YouTube视频的日期和链接。我正在使用猫鼬作为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');
您的 GET 请求
应该有效,因为浏览器默认执行 GET 请求。请尝试以下操作。
app.get("/database", function(req, res) {
Entry.find(function(err, data) {
if(err) {
console.log(err);
} else {
console.log(data);
}
});
});
就测试您的POST路由而言,请为Google Chrome安装一个名为Postman的插件。您可以使用它执行各种请求。它非常适合测试目的。
相关文章:
- 如何使用文档的ID从mongoDB集合中删除文档
- 我的 Meteor 项目如何通过服务器端 MongoDB/集合查找查询可靠地显示信息
- 如何使用express/mongoose和客户端JS将HTML类发布到mongoDB集合中
- 更新MongoDB集合中数组中的对象
- 正在将mongoDB集合导入Express Model
- 如何使用nodejs在mongodb集合中搜索重音字符
- 在 MongoDB 集合中查找字符串
- 无法在node.js中使用MongoClient列出mongodb集合中的文档
- 正确的MongoDB集合结构,包括Meteor中的值数组(不带键)
- 如何使用承诺保存多个 mongodb 集合
- 如何在更新时从 mongodb 集合中删除字段
- 在 Meteor 中,如何使表单加载从先前从 MongoDB 集合中提取的插入对象预填充
- Meteor MongoDB 集合无法访问 Meteor 发布
- 访问 Meteor 中的原生 mongoDB 集合
- 计算 mongodb 集合中的最小值、最大值和平均值
- 使用mongoose访问现有的mongodb集合
- MongoDB集合上的MapReduce为空
- 如何在数组中保存mongodb集合?同时将mongoose与expressJS一起使用
- 获取带有节点的mongodb集合
- 如何从nodejs中的find返回,mongoose mongodb集合