Search code examples
expressmongoosemongoose-schemamongoose-populatemongoosastic

Mongoose Schema RESTfull API and getone


Hi i need create RESTfull API with mongoose and express for fetch data of hotels data and i have a problem. let me show you. I need create this schema of DB.

 {
"hotels" : [{

"name" : "Hotel Emperador",
"stars" : "3",
"images" :[....],
"price" : "1596",
},
...]

}`

I am using mongoose and i created this schema

const hotelSchema = new mongoose.Schema({
    hotels:[{
    id : Number,
    name: String,
    stars: String,
    images: [String],
    price: String
    }]
  });

  const hotel = mongoose.model('hotel', hotelSchema);

I used hotel.save() method for save this

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"
    },...]

the question is the schema above is ok for my requirement of data base? on mongo Atlas show this:

mongoatlas

Well my main issue is because when i run this code do not obtain the array hotels

 hotel.find({},function(err,result){
        if(err){
            console.log(err)
        } else {
            console.log(result)
               }

i get this( console.log(result) and this has sense because i have an array before my object hotels.

[
  {
    _id: 5ee30d871e42964f0f3b3a10,
    hotels: [ [Object], [Object], [Object], [Object], [Object] ],
    __v: 0
  }
]

I needed do something how this for get all my nested objects inside the array

 hotel.findOne({ _id:"5ee30d871e42964f0f3b3a10"},function(err,result){
        if(err){
            console.log(err)
        } else {
            console.log(result)
               }

And here i need you help beacuse i cant find one method for get One hotel inside my array can you help me? i need the way for obtein with mongose a response how this

{
"name" : "Hotel Emperador",
"stars" : "3",
"images" :[....],
"price" : "1596",
}

Thanks for your help.


Solution

  • The problem is that you are storing all your hotel objects a single hotel document. To achieve the behaviour you want with ease, you can modify your schema as follows:

    const HotelSchema = new mongoose.Schema({
        name: String,
        stars: String,
        images: [String],
        price: String
    });
    const Hotel = mongoose.model('hotel', HotelSchema);
    

    To insert your list of hotels to the collection:

    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.
    ]);
    

    Finally, do the following to retrieve a single hotel from the collection:

    const hotel = await Hotel.findOne({});
    

    I hope this helps.