【发布时间】:2020-02-27 20:03:30
【问题描述】:
处理来自 MongoDb 的数据的问题
连接MongoDb成功,
但是在 find 命令上,它应该返回一个空集合,但没有返回任何内容。
可能是什么问题,或者如何通过一些错误消息对其进行监控。
谢谢。
项目依赖
"dependencies": {
"body-parser": "^1.19.0",
"epxress": "0.0.1-security",
"express": "^4.17.1",
"nodemon": "^2.0.2"
}
猫鼬.js
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/ListsDB', { useNewUrlParser: true, useUnifiedTopology: true}).then( ()=> {
console.log("Connected to MongoDbB successfully ");
}).catch( (e) => {
console.log("Error while attempting to connect to MongoDB");
console.log(e);
});
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
module.exports = {
mongoose
};
list.model.js
const mongoose = require('mongoose');
const ListSchema = new mongoose.Schema({
title: {
type: String,
required: true,
minlength: 1,
trim: true
}
})
const List = mongoose.model('List', ListSchema);
module.exports = { List }
app.js 不工作
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const { List, Task } = require('./db/models');
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next()
})
app.get('/lists', (req,res) => {
// We want to return an array of all the lists in the database
List.find({}).then( (err, lists)=> {
res.send(lists)
})
})
app.listen(3000, () => {
console.log("Server is listening on port 3000");
})
【问题讨论】:
-
你的意思是
res.json(lists)? -
不,我认为 res.send(lists) 是正确的。
-
你在 app.js 中导入列表了吗?你检查过你的控制台错误吗?
-
@Shl 你能查一下吗?
-
@Juhil Somaiya 是的,是的,而且错误没有返回任何东西,怀疑它的 mongo 问题,但不知道如何监控它。
标签: javascript node.js mongodb express mongoose