[NodeJs] NoSQL MongoDB 연동하기 (검색/추가/삭제/갱신)

2021. 4. 30. 01:58 JavaScript BackEnd/Node.js, Express

 

설치하기

https://www.npmjs.com/package/mongojs

1. npm install mongodbjs

 

  • 구현
    • Connection
var mongojs = require('mongojs');
var db = mongojs('localhost/test', ['board']);
db.on('error', function(err) {
	console.log(err);
});

db.on('connection', function() {
	console.log('connected');
});
    • Find
db.board.find(function(err, docs) {
	console.log(arguments);
	for (var i = 0; i <docs.length; i++) {
		console.log(docs[i].id + ", " + docs[i].title +", " +
				docs[i].content +", " + docs[i].writer);
	}
});
db.collection.find(function(err,array){});
db.collection.find({cKey:cVal}).toArray(function(err,array){});    
db.collection.find({cKey:cVal},{sKey:true, sKey:false}).toArray(function(err,array){});
db.collection.findOne({cKey:cVal}, function(err,obj){});
db.collection.find().sort({name:1}, function(err, array){});
    • Save / Insert
db.board.insert({_id:5, title:'new', content:'new content', writer:'ggiggi'});
    • Delete    
db.board.remove({_id:3});
    • Update
db.board.update({_id:2}, {$set:{writer:'hiru'}});

 

출처 : ourcstory.tistory.com/29?category=664896