【问题标题】:Trouble rendering of documents with referenced fields on Vue.js mongoose在 Vue.js mongoose 上无法渲染带有引用字段的文档
【发布时间】:2021-03-30 09:14:36
【问题描述】:

最近,我拿起了 Vue.js 和 Mongoose 来开发一个个人项目,主要是在某款网络游戏中跟踪材料的手头数量。

不同的菜肴需要不同的食材。 Lotus Seed - Bird Egg soup, Jewelry SoupJade Parcels 都需要不同数量的 Lotus Head 作为其成分。 我通过在成分集合中使用updateOne 来更新成分的数量。

不幸的是,我最初将成分嵌入食物/菜肴中,我意识到这是有问题的 最近,因为实际上你只是计算你目前拥有的成分。

所以食物文件现在看起来像这样

{
    "_id" : ObjectId("5fca4ada32195d5814510242"),
    "foodName" : "Lotus Seed and Bird Egg Soup",
    "onHandQty" : 20,
    "ingredients" : [ 
        "5fca481432195d581451023f", 
        "5fca483932195d5814510240", 
        "5fca48a232195d5814510241"
    ]
}

我阅读了 Mongoose 的 populate(),并测试输出一种食物/菜肴。不幸的是,在尝试了该代码之后,Vue.js 前端没有任何结果。

服务器/模型/Food.js

const { Router } = require('express');
const FoodItem = require('../../models/Food');
const IngredientItem = require('../../models/Ingredient');

const router = Router()

router.get('/', async(req, res) =>{
    try {
        const food = await FoodItem.findOne({
            foodName: 'Lotus Seed and Bird Egg Soup'
        }).populate('ingredients').
        exec(function (err, food) {
          if (err) return handleError(err);
          console.log('The food is %s', food.foodName);
        });
        res.send(food);
    } catch (error) {
        res.status(500).json({
            message: error.message
        })
    }
});

module.exports = router

渲染成分的部分组件

client/src/components/Food.vue

<div class="tile is-ancestor">
                    <div class="tile">
                        <div class="tile is-parent">
                            <div class="tile is-child box">
                                <template v-if="food.ingredients">
                                    <div class="ingredients-block">
                                        <p>Ingredients List:</p>
                                        <ul class="ingredients-list">
                                            <li class="row" v-for="ingredient in food.ingredients" :key="ingredient._id">
                                                <div id="ingredient-image-container">
                                                    <img class="image is-64x64" :src="require(`../assets/images/food_inv/${ingredient.imagePath}.png`)" alt="ingredient.ingredientName" :title="ingredient._id">
                                                    {{ingredient.ingredientName}}
                                                </div>
                                                <div class="required-qty-container">
                                                    <!-- <i class="material-icons" id="required-inner-qty">food_bank</i> -->
                                                    Required:
                                                    {{ ingredient.requiredQty }}
                                                </div>
                                                <div class="on-hand-qty-container">
                                                    <p>On Hand:</p>
                                                    <input v-if="ingredient.onHandQty < ingredient.requiredQty" class="input is-danger on-hand-input" type="number" v-model="ingredient.onHandQty" min="0">
                                                    <input v-else class="input is-primary on-hand-input" type="number" v-model="ingredient.onHandQty" min="0">
                                                    <!-- <button class="button is-primary save-button" @click="test({ingredient_id: ingredient._id, onhandqty: ingredient.onHandQty})"><i class="material-icons">save</i></button> -->
                                                    <button class="button is-primary save-button" @click="$emit('update-qtys', {ingredient_id: ingredient._id, onhandqty: ingredient.onHandQty})"><i class="material-icons">save</i></button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>

Github 上的整个项目:Food Inventory

【问题讨论】:

    标签: node.js mongodb express mongoose vuejs2


    【解决方案1】:

    快速修复,

    • 将食物架构的成分字段从对象更改为数组,
    const foodSchema = new mongoose.Schema(
        {
            foodName: String,
            imagePath: String,
            effect: String,
            onHandQty: Number,
            // correct this to array
            ingredients:  [{
                type: mongoose.Schema.Types.ObjectId,
                ref: 'Ingredient'
            }]
        }
    );
    
    • 有两种方法可以调用 mongoose 方法,第一种是带回调的 exec(),第二种不带 exec() 回调,
    • 带有您已使用购买的回调的 exec 需要从 exec 调用函数内部发送响应(res.send(food)res.json(food)),
    router.get('/', async(req, res) =>{
        try {
            await FoodItem.find()
                .populate('ingredients')
                .exec(function (err, food) {
                    if (err) return handleError(err);
                    console.log('The food is %s', food);
                    // put response here
                    res.json(food);
                });
        } catch (error) {
            res.status(500).json({ message: error.message })
        }
    });
    
    • 执行无回调
    router.get('/', async(req, res) =>{
        try {
            const food = await FoodItem.find() 
                .populate('ingredients')
                .exec();
            res.json(food);
        } catch (error) {
            res.status(500).json({ message: error.message })
        }
    });
    

    【讨论】:

    • 您好,感谢您的回答。不幸的是,组件没有输出。但是暂时,当const food = await FoodItem.findOne({ ... }) 部分更改为const food = await FoodItem.find() 时,食物组件列出了数据库中的所有食物。我想问一下我在client/src/components/Food.vue 部分&lt;ul class="ingredients-list"&gt;&lt;li class="row" v-for="ingredient in food.ingredients" :key="ingredient._id"&gt; 上的代码是否有问题 v-for 部分上的点符号是否不够?
    • 我认为您刚刚在您的仓库中添加了客户端代码,我会尽快检查并更新您。
    • 我已经测试了服务器端代码以及更正后我添加了答案,所以客户端可能存在一些问题。我会检查并更新你。
    • 是的,我今天刚看到客户端文件不存在,所以我修复了我的本地仓库以推送它。慢慢来
    • 哦,我明白了,除此之外,imagePath 上还有不匹配的名称。我真的在这方面学到了很多。谢谢百万人!
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 2021-02-07
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 2018-08-31
    • 2017-09-24
    相关资源
    最近更新 更多