【发布时间】:2020-10-01 23:00:06
【问题描述】:
您好,我需要使用 mongoose 和 express 创建 RESTfull API 来获取酒店数据,但我遇到了问题。让我演示给你看。 我需要创建这个 DB 架构。
{
"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)
}
在这里我需要你的帮助,因为我找不到在我的阵列中获得一间酒店的方法,你能帮我吗?我需要用 mongose 获得方法来响应这个
{
"name" : "Hotel Emperador",
"stars" : "3",
"images" :[....],
"price" : "1596",
}
感谢您的帮助。
【问题讨论】:
-
这能回答你的问题吗? Find in Double Nested Array MongoDB
标签: express mongoose mongoose-schema mongoose-populate mongoosastic