处理来自 MongoDb 的数据时出现问题
已成功连接 MongoDb ,
但是在 find 命令上,它应该返回一个空集合,但什么也没有返回。
可能是什么问题,或者如何通过某些错误消息来监控它。
谢谢。
项目依赖
"dependencies": {
"body-parser": "^1.19.0",
"epxress": "0.0.1-security",
"express": "^4.17.1",
"nodemon": "^2.0.2"
}
Mongoose .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
};
列表.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");
})
最佳答案
尝试使用此语法
app.get('/lists', (req,res) => {
List.find({}).then( lists => {
res.send(lists)
}).catch(err =>
console.log(err)
);
})
关于javascript - nodejs mongodb,从数据库没有得到结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60431628/