Created
July 6, 2018 17:34
-
-
Save yukeehan/043df40ce5865786d9531be7df4ef123 to your computer and use it in GitHub Desktop.
Learning how to use Mongoose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require("mongoose"); | |
mongoose.connect("mongodb://localhost/food_app"); | |
var foodSchema = new mongoose.Schema({ | |
name: String, | |
taste: String, | |
isGood: Boolean, | |
price: Number | |
}); | |
/*To use our schema definition, we need to convert our blogSchema | |
into a Model we can work with. To do so, | |
we pass it into mongoose.model(modelName//the singular version of the model//, schema):*/ | |
var Food = mongoose.model("Food", foodSchema); | |
//adding a new food to the DB(food_app) | |
// var Tofu = new Food({ | |
// name: "Mapo Tofu", | |
// taste: "Spicy", | |
// isGood: true, | |
// price: 15 | |
// }); | |
// var Hotpot = new Food({ | |
// name: "Huoguo", | |
// taste: "Spicy", | |
// isGood: true, | |
// price: 50 | |
// }); | |
// Tofu.save(function(err, food){ //a callback function; food refer to what is DB sends back | |
// if(err){ | |
// console.log("There is an error!"); | |
// }else{ | |
// console.log("We just save a food into DB!"); | |
// console.log(food); | |
// } | |
// }); | |
// Hotpot.save(function(err, food){ | |
// if(err){ | |
// console.log("There is an error!"); | |
// }else{ | |
// console.log("We just save a food into DB!"); | |
// console.log(food); | |
// } | |
// }); | |
Food.create({ | |
name: "Gongbao Chicken", | |
taste: "Spicy", | |
isGood: true, | |
price: 20 | |
}, function(err, food){ | |
if(err){ | |
console.log("Nooo Error!!!"); | |
} else { | |
console.log(food); | |
} | |
}); | |
//retrive all the data in the DB | |
Food.find({},function(err, foods){ | |
if(err){ | |
console.log("There is an error!!!"); | |
} else { | |
console.log("Here are all the chinese foods"); | |
console.log(foods); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment