Mongoose

目录

Connect database and insert data

Read

update and delete

relation and embedding

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值