仅当mongoDB节点JS

时间:2017-08-09 07:27:02

标签: 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 });        
        }
    })
})

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

只需检查成分阵列的长度:

<!-- 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) { %>
        ... 
        ...