Как извлечь атрибуты объекта из массива объектов, если тип каждого объекта - mongoose.Schema.Types.ObjectId? - PullRequest
0 голосов
/ 06 июня 2019

У меня есть две модели, названные как еда и ресторан. У модели ресторана есть множество продуктов с типом как mongoose.Schema.Types.ObjectId & ref as Food. Я пытаюсь получить доступ к атрибутам объекта массива продуктов.

Я ожидал, что продукты - это массив объектов, если я получу console.log (restaurant), но получаю массив идентификаторов. Может быть, это правильно, потому что тип объекта массива продуктов был objectId. Но тогда как мне получить доступ к атрибутам каждого элемента в массиве продуктов. Я хотел сделать restaurant.foods [0] .someAttributeOfFood. Но он, очевидно, не работает, так как restaurant.foods - это массив идентификаторов объектов.

Модель ресторана


const restaurantSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    foods: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Food"
        }
],
    image: {
        type: String
    }
});

module.exports = mongoose.model("Restaurant",restaurantSchema);```


Food model
```const mongoose = require('mongoose');

const foodSchema = new mongoose.Schema({
            name: {
                type: String,
                required: true
            },
            cost:{
                type: Number,
                required: true
            },
            discount:{
                type: Number
            },
            image: {
                type:String
            }
});

module.exports = mongoose.model("Food",foodSchema);```


EJS CODE TRYING TO ACCESS ATTRIBUTES OF OBJECT
```  <% restaurant.foods.forEach(function(food){ %>
         <div class="row">
             <div class="col-md-12">
                 <strong>Cost ₹<%= food.cost %></strong>
                 <span class="pull-right">Discount ₹<%= food.discount %></span>
                  <p>
                     <%= food.name %>
                  </p>                
                      <a class="btn btn-xs btn-warning" 
                      href="/restaurants/<%= restaurant._id %>/foods/<%= food._id %>/edit">
                      Edit
                      </a>

                      <form id="delete-form" action="/admin/restaurants/<%= restaurant.id %>/foods/<%= food._id %>?_method=DELETE" method="POST" >
                            <button class="btn btn-xs btn-danger">Delete</button>
                      </form>           
             </div>
         </div>```






//CREATE route for new food
```router.post("/admin/restaurants/:id/foods", function(req, res){

    Restaurant.findById(req.params.id,function(err, restaurant) {
        if(err){
            console.log(err);
            res.redirect("/restaurants")
        }else{
            Food.create(req.body.food,function(err,food){
                if(err){

                    console.log(err);
                }else{
                    restaurant.foods.push(food);
                    restaurant.save();
                    console.log(restaurant)
                    res.redirect("/admin/restaurants/" + restaurant._id);
                }
            });
        }
    });
});

console.log (рестораны) Фактическая мощность

   [ 5cf82102b58b5883d43e9074,

 ],
  _id: 5cf820a3b58b5883d43e9073,
  name: 'Skylark',
  image: 'https://cdn4.buysellads.net/uu/1/3386/1525189943-38523.png',
  __v: 4 }```

Maybe expected output

console.log(restaurants) after adding food & saving
```{ foods:
   [ {
       _id: 5cf82102b58b5883d43e9074,
       name: burger,
       cost: 54,
       discount: 12,
       image: something
      },

 ],
  _id: 5cf820a3b58b5883d43e9073,
  name: 'Skylark',
  image: 'https://cdn4.buysellads.net/uu/1/3386/1525189943-38523.png',
  __v: 4 }```

1 Ответ

0 голосов
/ 06 июня 2019

посмотрите на https://mongoosejs.com/docs/populate.html

пример:

const storySchema = Schema({
  authors: [{ type: Schema.Types.ObjectId, ref: 'Person' }],
  title: String
});



const story = await Story.findOne({ title: 'Casino Royale' }).populate('authors');
story.authors; // `[]`
...