javascript - 仅当 mongoDB Node JS 上存在集合时才显示给客户端

标签 javascript node.js mongodb mongoose

我在 Mongoose 上定义了这个架构模型:

var mongoose = require("mongoose");

var IngredientSchema = new mongoose.Schema({
    name:String,
    number:Number,
    exist:Boolean,
    photoName:String
})

module.exports = mongoose.model("Ingredient", IngredientSchema);

我想在网页上显示不同的结果,具体取决于数据库中是否已创建成分。

这是我迄今为止尝试过的方法(但不起作用):

<!-- Check if inventory is empty or not, and display accordingly -->
<% if ( ! ingredients) { %>

    <p>Add you first ingredient to the inventory !!</p>

<% } else { %>

    <%  ingredients.forEach(function(ingredient) { %>
    ... 
    ...

这是我的路线:

// Index route
app.get("/inventory", function(req, res) {
    Ingredient.find({}, function(err, allIngredients) {
        if (err) {
            console.log(err);
        } else {
            res.render("inventory", { ingredients:allIngredients });        
        }
    })
})

非常感谢您的帮助。

最佳答案

只需检查成分数组的长度:

<!-- Check if inventory is empty or not, and display accordingly -->
    <% if (!ingredients.length) { %>

        <p>Add you first ingredient to the inventory !!</p>

    <% } else { %>

        <%  ingredients.forEach(function(ingredient) { %>
        ... 
        ...

关于javascript - 仅当 mongoDB Node JS 上存在集合时才显示给客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45584180/

相关文章:

javascript - 我需要比较并记录同一Javascript/XML项目的2个版本

跨类和文件的 Javascript 原型(prototype)

html - YouTube 缩略图破坏了 maxres 使用

node.js - Mongoose 总是返回空数组?

javascript - 带有钩子(Hook)的功能组件导致 "cannot read property map of undefined"

javascript - 自 Jest 26+ 以来如何兑现 promise

javascript - 背景颜色悬停淡入淡出效果 CSS

javascript - nodejs 流可读卡在第一个可读对象

node.js - 将应用程序部署到 Heroku - 我遇到内部服务器错误

mongodb - Mongodb 按 DateTime 查询记录是否比按 String 更快?