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

How to update and read a collection in MongoDB using Mongoose

本文关键字:MongoDB 集合 读取 何使用 Mongoose 更新      更新时间:2023-09-26

我在处理一个项目时遇到问题。我想创建一个数据库,我可以在其中存储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的插件。您可以使用它执行各种请求。它非常适合测试目的。