我在MongoDB中建立了一个名为entertainment的数据库,其中包含一个名为medias的集合,该集合中包含JSON数据。
当我使用Postman呼叫数据库时:http://localhost:8000/data
返回了一个空数组。
下面是我的全部代码:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
require("dotenv").config();
const uri = `mongodb+srv://tyrellc:${process.env.MONGO_PASSWORD}@entertainmentapp.jtcf92n.mongodb.net/?retryWrites=true&w=majority`;
async function connect() {
try {
await mongoose.connect(uri);
console.log("Connected to MongoDB");
} catch (error) {
console.log(error);
}
}
mongoose.set("strictQuery", false);
connect();
app.listen(8000, () => {
console.log("Express Server Started port:8000");
});
const collectionSchema = new mongoose.Schema({
_id: { type: mongoose.Schema.Types.ObjectId, required: true },
title: { type: String, required: true },
thumbnail: {
trending: {
small: { type: String, required: true },
large: { type: String, required: true },
},
regular: {
small: { type: String, required: true },
medium: { type: String, required: true },
large: { type: String, required: true },
},
},
year: { type: Number, required: true },
category: { type: String, required: true },
rating: { type: String, required: true },
isBookmarked: { type: Boolean, default: false },
isTrending: { type: Boolean, default: true },
});
const Collection = mongoose.model("Collection", collectionSchema, "medias");
app.get("/data", async (req, res) => {
const data = await Collection.find();
res.json(data);
});
运行应用程序时,我会获得两个控制台日志:Express Server Started port:8000
和Connected to MongoDB
。
这是我的JSON数据在MongoDB中的样子:
{"_id":{"$oid":"63c733940231fb2f67b5344e"},"title":"Beyond Earth","thumbnail":{"trending":{"small":"./assets/thumbnails/beyond-earth/trending/small.jpg","large":"./assets/thumbnails/beyond-earth/trending/large.jpg"},"regular":{"small":"./assets/thumbnails/beyond-earth/regular/small.jpg","medium":"./assets/thumbnails/beyond-earth/regular/medium.jpg","large":"./assets/thumbnails/beyond-earth/regular/large.jpg"}},"year":{"$numberInt":"2019"},"category":"Movie","rating":"PG","isBookmarked":false,"isTrending":true}
我研究过多元化,并尝试过:const Collection = mongoose.model("Collection", collectionSchema, "medias");
const Collection = mongoose.model("Collection", collectionSchema, "media");
const Collection = mongoose.model("media", collectionSchema);
const Collection = mongoose.model("medias", collectionSchema);
似乎什么都做不到。有人知道我做错了什么吗?
MongoDB图谱数据库:
2条答案
按热度按时间798qvoo81#
必须指定要使用的数据库。可以在连接字符串中指定,如下所示:
或者,如果您愿意,可以将其作为选项传递给
mongoose.connect()
,如下所示:dfuffjeb2#
根据mongoose文档,
find()
方法接受参数:筛选器类型对象必需,可选参数。如果你想从模型中检索所有文档,你应该传递一个空对象
{}
作为过滤器。