【问题标题】:How to retrieve attributes of an object from an array of objects if the type of each object is mongoose.Schema.Types.ObjectId?如果每个对象的类型是 mongoose.Schema.Types.ObjectId,如何从对象数组中检索对象的属性?
【发布时间】:2019-10-21 10:07:07
【问题描述】:

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

如果我使用 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 }```

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 2013-09-03
      相关资源
      最近更新 更多