无法弄清楚服务器为什么返回空字符串。在本地主机端口3000上运行服务器,数据库名称为“ cocktails”,集合名称为“ Cocktails”。服务器连接到数据库正常。
服务器:
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const PORT = process.env.PORT || 3000;
let Cocktail = require("./schemas/cocktail.model");
const router = express.Router();
const URL =
"mongodb+srv://owner:<password>@cluster0-i3tky.mongodb.net/test?retryWrites=true&w=majority";
app.use(cors());
app.use(bodyParser.json());
mongoose
.connect(URL, { useUnifiedTopology: true, useNewUrlParser: true })
.then(console.log("MongoDB database connection has been established."))
.catch(err => {
console.log(err);
});
router.get("/", (req, res) => {
Cocktail.find({}, (err, cocktails) => {
if (err) {
console.log(err);
} else {
res.json(cocktails);
}
});
});
app.use("/", router);
app.listen(PORT, () => {
console.log("Server is running on Port: " + PORT);
});
但是,用get函数代替router.get('/', (req,res)=> res.json({msg: 'test works'})
-邮递员返回测试消息。
猫鼬模型:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let Cocktail = new Schema({
name: {
type: String
},
ingredients: {
type: Array
},
measurements: {
type: Array
}
});
module.exports = mongoose.model("Cocktail", Cocktail, "cocktails");
为什么快递服务器返回一个空数组?