如果每个对象的类型是 mongoose.Schema.Types.ObjectId,如何从对象数组中检索对象的属性?

How to retrieve attributes of an object from an array of objects if the type of each object is mongoose.Schema.Types.ObjectId?

我有两个名为 food & restaurant 的模型。餐厅模型有一系列食物,类型为 mongoose.Schema.Types.ObjectId & ref 为食物。我正在尝试访问 foods 数组对象的属性。

如果我 console.log(餐厅),我希望食物是一组对象,但我得到的是一组 ID。也许这是正确的,因为食物数组的对象类型是 objectId。但是我如何访问 foods 数组中每个元素的属性。我想做 restaurant.foods[0].someAttributeOfFood。但它显然不起作用,因为 restaurant.foods 是一个 objectID 数组。

餐厅模式


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 }```

调查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; // `[]`