Databases - NoSQL

NoSQL

MongoDB

npm install --save mongodb

Database connection

const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;

let _db;

const mongoConnect = (callback =>{
  MongoClient.connect(
    ""
  )
    .then(client => {
      console.log("connected");
      _db = client.db();
      callback();
    })
    .catch(err => {
      console.log(err);
      throw err;
    });
  
});

const getDb = () =>{
  if(_db) {
    return _db;
  }
  throw 'No database found'
}
exports.mongoConnect = mongoConnect;
exports.getDb = getDb;
db.collection('name').insertOne({})
.find()

Mongo Shell Basics

commands

  • help
  • show dbs
    • show database names
  • use
    • use database or create one if not exist
    • use demo
  • insert
    • db.dog.insert({name: "congcong"})
  • show collections
    • show  collections in current database
  • find
    • db.dog.find()
    • db.dog.fing({name: "xxx", sex: "uuu"})
  • update
    • db.dog.update({name:"xxx"},{$set: {sex:"???"}})
  • remove
    • db.dogs.remove({sex: "hehe"})
  • db.collection.drop
    • delete all in the database
    • db.dogs.drop()

 

MongoDB cloud server

check data base, use connect to mongo shell

then follow the instruction

 

 

Mongoose

 

 

tool help to interact with MongoDB in JS

npm install mongoose --save
const mongoose = require("mongoose");

mongoose.connect("mongoDB atlas url");

// define pattern of the data
// pass JS object
// property: type
var sampleSchema = mongoose.Schema({
    name: String,
    age: Number
});

// pattern compiled into a model
// "Name" name of singular version of out model, start with uppercase
var Sample  = mongoose.model("Sample",sampleSchema);

// create a new object
var entry =  new Sample({
    name: "hehe",
    age: 7
});

// the following can use promise style then() and catch()

// save may not be sucessful, so to check use a call back function
// (error, creature)
entry.save((err,creature) => {
    if(!err){
    }
});

// create: new and save all at once
Sample.create({
    name:
    age:
},(err, creature) =>{

});

// find
Sample.find({}, (err, creature) =>{
    if(!err)
})
// select certain features in the database after find
.select('title price');

// find single element
Sample.findById(id, (err,found)=>{
});

//find and remove
Sample.findByIdAndRemove()

//Population is the process of automatically replacing the specified paths in the
//document with document(s) from other collection(s).
// populate the details

User.findOne().populate("posts").exec((err,user)=>{

});

Add own method

userSchema.methods.addToCart= function(){

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值