express - Mongoose Schema RESTfull API 和 getone
问题描述
嗨,我需要使用 mongoose 和 express 创建 RESTfull API 来获取酒店数据的数据,但我遇到了问题。让我演示给你看。我需要创建这个数据库架构。
{
"hotels" : [{
"name" : "Hotel Emperador",
"stars" : "3",
"images" :[....],
"price" : "1596",
},
...]
}`
我正在使用猫鼬,我创建了这个模式
const hotelSchema = new mongoose.Schema({
hotels:[{
id : Number,
name: String,
stars: String,
images: [String],
price: String
}]
});
const hotel = mongoose.model('hotel', hotelSchema);
我使用 hotel.save() 方法来保存它
const hotels = new hotel( {hotels:[{
"name" : "Hotel Emperador",
"stars" : "5",
"images" :['https://media-cdn.tripadvisor.com/media/photo-s/03/01/e7/a1/hotel-bolivar.jpg'],
"price" : "1596"
},...]
问题是上面的架构可以满足我对数据库的要求吗?在 mongo Atlas 上显示:
那么我的主要问题是因为当我运行这段代码时没有获得数组酒店
hotel.find({},function(err,result){
if(err){
console.log(err)
} else {
console.log(result)
}
我得到了这个(console.log(result),这是有道理的,因为我的对象酒店之前有一个数组。
[
{
_id: 5ee30d871e42964f0f3b3a10,
hotels: [ [Object], [Object], [Object], [Object], [Object] ],
__v: 0
}
]
我需要做一些事情来获取数组中的所有嵌套对象
hotel.findOne({ _id:"5ee30d871e42964f0f3b3a10"},function(err,result){
if(err){
console.log(err)
} else {
console.log(result)
}
在这里我需要你的帮助,因为我找不到在我的阵列中获得一间酒店的方法,你能帮我吗?我需要用 mongoose 获得方法来回应如何
{
"name" : "Hotel Emperador",
"stars" : "3",
"images" :[....],
"price" : "1596",
}
谢谢你的帮助。
解决方案
问题是您将所有酒店对象存储在一个hotel
文档中。为了轻松实现您想要的行为,您可以按如下方式修改您的架构:
const HotelSchema = new mongoose.Schema({
name: String,
stars: String,
images: [String],
price: String
});
const Hotel = mongoose.model('hotel', HotelSchema);
要将您的酒店列表插入到集合中:
await Hotel.create([{
"name" : "Hotel Emperador",
"stars" : "5",
"images" :['https://media-cdn.tripadvisor.com/media/photo-s/03/01/e7/a1/hotel-bolivar.jpg'],
"price" : "1596"
},
... // other hotel elements go here.
]);
最后,执行以下操作以从集合中检索单个酒店:
const hotel = await Hotel.findOne({});
我希望这有帮助。
推荐阅读
- javascript - React 导入和渲染其他组件在没有工具的情况下无法正常工作
- excel - 条件格式,颜色与上面数字一样多的单元格
- python - 在按键上停止语音识别
- javascript - 如何使用 v-data-table 上下移动行?
- python - 如何从python pandas中的多个excels文件中删除重复记录
- python - Python 3:将元组转换为字典
- jquery - 如何将不同时间收集的两个不同输入关联起来,并在需要时召回它们?
- docker - docker 服务显示正在运行但未在 docker 容器中列出的图像
- reactjs - 用 useReducer 钩子替换 redux 的最佳实现是什么?
- python - python中的字符串列表