我在 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/