node.js操作mongodb簡(jiǎn)單示例分享
更新時(shí)間:2017年05月25日 10:36:27 作者:WhoAmMe
MongoDB是基于Javascript語言的數(shù)據(jù)庫,存儲(chǔ)格式是JSON,而Node也是基于JavaScript的環(huán)境(庫),所以node和mongoDB的搭配能減少因?yàn)閿?shù)據(jù)轉(zhuǎn)換帶來的時(shí)間空間開銷。今天我們來看看如何通過node.js來操作MongoliaDB
前兩篇文章我們介紹了nodejs操作redis和MySQL,下面簡(jiǎn)要測(cè)試一下nodejs操作mongodb:
首先安裝nodejs mongodb
npm install mongodb
代碼
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
var db = new mongodb.Db('mydb', server, {safe:true});
//連接db
db.open(function(err, db){
if(!err){
console.log('connect db');
// 連接Collection(可以認(rèn)為是mysql的table)
// 第1種連接方式
// db.collection('mycoll',{safe:true}, function(err, collection){
// if(err){
// console.log(err);
// }
// });
// 第2種連接方式
db.createCollection('mycoll', {safe:true}, function(err, collection){
if(err){
console.log(err);
}else{
//新增數(shù)據(jù)
// var tmp1 = {id:'1',title:'hello',number:1};
// collection.insert(tmp1,{safe:true},function(err, result){
// console.log(result);
// });
//更新數(shù)據(jù)
// collection.update({title:'hello'}, {$set:{number:3}}, {safe:true}, function(err, result){
// console.log(result);
// });
// 刪除數(shù)據(jù)
// collection.remove({title:'hello'},{safe:true},function(err,result){
// console.log(result);
// });
// console.log(collection);
// 查詢數(shù)據(jù)
var tmp1 = {title:'hello'};
var tmp2 = {title:'world'};
collection.insert([tmp1,tmp2],{safe:true},function(err,result){
console.log(result);
});
collection.find().toArray(function(err,docs){
console.log('find');
console.log(docs);
});
collection.findOne(function(err,doc){
console.log('findOne');
console.log(doc);
});
}
});
// console.log('delete ...');
// //刪除Collection
// db.dropCollection('mycoll',{safe:true},function(err,result){
// if(err){
// console.log('err:');
// console.log(err);
// }else{
// console.log('ok:');
// console.log(result);
// }
// });
}else{
console.log(err);
}
});
相關(guān)文章
詳解node單線程實(shí)現(xiàn)高并發(fā)原理與node異步I/O
本篇文章主要介紹了node單線程實(shí)現(xiàn)高并發(fā)原理與node異步I/O ,具有一定的參考價(jià)值,有興趣的可以了解一下2017-09-09
npm?install編譯時(shí)報(bào)"Cannot?read?properties?of?null?(r
這篇文章主要給大家介紹了關(guān)于npm?install編譯時(shí)報(bào)“Cannot?read?properties?of?null?(reading?‘pickAlgorithm‘)“錯(cuò)誤的解決辦法,文中將解決方法介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07
no-vnc和node.js實(shí)現(xiàn)web遠(yuǎn)程桌面的完整步驟
這篇文章主要給大家介紹了關(guān)于no-vnc和node.js實(shí)現(xiàn)web遠(yuǎn)程桌面的完整步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Node.js模塊Modules的使用實(shí)戰(zhàn)教程
這篇文章主要介紹了Node.js模塊Modules的使用,模塊就是一個(gè)聲明了裝飾器@Module()的類。裝飾器@Module()提供了元數(shù)據(jù),以便讓Nest組織應(yīng)用程序結(jié)構(gòu)2023-04-04
使用nodejs、Python寫的一個(gè)簡(jiǎn)易HTTP靜態(tài)文件服務(wù)器
這篇文章主要介紹了使用nodejs、Python寫的一個(gè)簡(jiǎn)易HTTP靜態(tài)文件服務(wù)器,分為nodejs和Python兩個(gè)版本,用類似淘寶的CSS、JS文件加載方式處理靜態(tài)文件加載,需要的朋友可以參考下2014-07-07

