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(){
}