首页 > 解决方案 > 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",
}

谢谢你的帮助。

标签: expressmongoosemongoose-schemamongoose-populatemongoosastic

解决方案


问题是您将所有酒店对象存储在一个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({});

我希望这有帮助。


推荐阅读