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

时间:2019-06-05 21:26:42

标签: node.js mongodb mongoose mongoose-schema

我有两个型号分别为食品和餐厅。餐厅模型包含一系列食物,其类型为mongoose.Schema.Types.ObjectId,而ref为Food。我正在尝试访问foods数组对象的属性。

如果我使用console.log(restaurant),我原本期望食物是一组对象,但是我得到的是一组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 }```

1 个答案:

答案 0 :(得分:0)

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