目录
Connect database and insert data
27017> show dbs
admin 40.00 KiB
config 60.00 KiB
fruitDB 40.00 KiB
local 80.00 KiB
shopDB 48.00 KiB
27017> use fruitDB
switched to db fruitDB
fruitDB> db.dropDatabase()
{ ok: 1, dropped: 'fruitDB' }
fruitDB> show dbs
admin 40.00 KiB
config 60.00 KiB
local 80.00 KiB
shopDB 48.00 KiB
Connect database and insert data
const mongoose = require('mongoose');
// Put the name of database at the end of the url
mongoose.connect('mongodb://localhost:27017/fruitsDB');
console.log("Connected successfully to server");
// Use schema to create mongo model
const fruitSchema = new mongoose.Schema({
name:String,
rating:Number,
review:String
});
const Fruit = mongoose.model('Fruit', fruitSchema);
const kiwi = new Fruit({
name: 'Kiwi',
rating:10,
review:"The best fruit"
});
const orange = new Fruit({
name: 'orange',
rating:4,
review:"Too sour for me "
});
const banana = new Fruit({
name: 'banana',
rating:3,
review:"wired texture"
});
Fruit.insertMany([kiwi,orange,banana],function(err){
if (err){
console.log(err);
}else{
console.log("Successlly saved all the fruits to fruitDB")
}
})
Read
Fruit.find(function(err,fruits){
if (err){
console.log(err);
}else{
#使用ejs来遍历每个fruit
fruits.forEach(function(fruit){
console.log(fruit.name);
})
}
})
update and delete
// update
Fruit.updateOne({_id:"638725ae666865a492f8d8be"},{name:'Peach'},function(err){
if(err){
console.log(err);
}else{
console.log("Successfully updated the document");
}
})
// delete
Fruit.deleteOne({name:'Peach'},function(err){
if(err){
console.log(err);
}else{
console.log("Successfully deleted the document");
}
})
// delete all name is Peach
Fruit.deleteMany({name:'Peach'},function(err){
if(err){
console.log(err);
}else{
console.log("Successfully deleted the document");
}
})
relation and embedding