몽고DB 소개
1 몽고DB 소개
MongoDB는 NoSQL 데이터베이스입니다.
테이블과 행의 형태로 데이터를 저장하는 대신 mongoDB에서 데이터를 객체의 형태로 저장합니다.
Mongoose는 ODM으로 MongoDB와 더 쉽게 통신할 수 있습니다.
이 시리즈에서 우리는에 대해 배울 것입니다
몽고DB와 몽구스
CRUD 애플리케이션
Mocha라는 테스트 프레임워크가 있습니다.
2 로컬에 MongoDB 설치 및 MongoDB에 연결
npm init -- 종속성을 추적합니다. npm install mongoose --save //connection.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/testaroo');
mongoose.connection.once('open', function(){
console.log('Connection is made');
}).on('error', function(error){
console.log('Connection error', error);
})
3 모델 및 컬렉션
파일: models/marioChar.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MarioCharSchema = new Schema({
name: String,
weight: Number
})
const MarioChar = mongoose.model('mariochar', MarioCharSchema)
module.exports = MarioChar;
// Now we can do the following
// var myChar = new MarioChar({ name: "Rayan", weight: 100 });
4 모카 테스트 소개
Mocha는 테스트 프레임워크입니다.
응용 프로그램 내에서 수행하는 데 사용합니다.
모든 것이 올바르게 작동하는지 확인하려면
먼저 모카를 설치하십시오npm install mocha --save.
테스트 스크립트demo_test.js를 폴더/test에 보관합니다.
데모_테스트.js
const mocha = require('mocha');
const assert = require('assert');
describe('Some demo tests', function(){
//Create tests
it('adds two numbers together', function(){
assert(2+3===5)
})
})
test에서 mocha 속성을 package.json로 설정합니다.
그리고 실행npm run test 5 MongoDB에 데이터 저장
const mocha = require('mocha');
const assert = require('assert');
const MarioChar = require('../models/mariochar');
describe('Some demo tests', function(){
//Create tests
it('Saves a record to the database', function(done){
var character = new MarioChar({
name: "Mario",
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
})
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
위의 함수는 character를 데이터베이스에 저장합니다.character.isNew는 객체가 생성되었지만 데이터베이스에 없는 경우 true를 반환합니다.
개체가 데이터베이스에서 발견되면 false를 반환합니다.save는 비동기 함수이므로 다음 테스트를 수행하려면 done 메서드를 통해 언제 완료되는지 명시적으로 알려야 합니다.
mogoose 자체 promise를 사용하는 대신 ES6 promise 사용
const mongoose = require('mongoose');
// Using ES6 promise instead mogoose's promise
mongoose.Promise = global.Promise
// Connect to mongodb
mongoose.connect('mongodb://localhost/testaroo');
mongoose.connection.once('open', function(){
...
}).on('error', function(error){
...
})
이 시점에서 연결이 설정되기 전에도 테스트가 실행되고 있습니다.
그렇게 하려면 연결 코드를 안에 넣어야 합니다before.
before(function(done){
mongoose.connect('mongodb://localhost/testaroo');
mongoose.connection.once('open', function(){
console.log('Conneciton is made');
done();
}).on('error', function(error){
console.log('Connection error', error);
})
})
연결이 설정될 때 명시적으로 알려주는 데 done을 사용했습니다.
6 컬렉션 삭제
컬렉션을 삭제하려면:mongoose.connection.collections.mariochars.drop()우리는 mariochars가 아니라 mariochar (복수화)를 쓰고 있지만 컬렉션을 mariochar로 선언했습니다. 이것이 mongodb가 작동하는 방식입니다.
한 테스트의 결과가 다른 테스트에 영향을 미치지 않도록 모든 테스트 전에 컬렉션을 삭제하려면 beforeEach
const mongoose = require('mongoose');mongoose.Promise = global.Promise
before(function(done){
// Connect to mongodb
...
})
beforeEach(function(done){
mongoose.connection.collections.mariochars.drop()
done()
})
7 기록 찾기
검색을 위해 모델에 find 또는 findOne 방법을 사용할 수 있습니다.
MarioChar.findOne({ name: "Mario"}).then(result => {
...
})
이 코드는 name==="Mario"인 첫 번째 일치 항목을 찾습니다.
우리의finding_test.js 파일은
const assert = require('assert');
const MarioChar = require('../models/mariochar');
describe('Some demo tests', function(){
beforeEach(function(done){
var character = new MarioChar({
name: "Mario",
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
})
//Create tests
it('Finding a record form the database', function(done){
MarioChar.findOne({ name: "Mario"}).then(result => {
assert(result.name === "Mario")
done();
})
})
})
8 개체 ID
컬렉션에서 ID별로 데이터를 검색하려면:
MarioChar.findOne({ _id: character._id }).then(result => {
assert(result._id === character._id)
done();
})
그러나 위의 코드는 다음과 같이 작동하지 않습니다.result._id===character._id는 false를 다음과 같이 반환합니다.result._id는 ObjectID 유형이고 character._id는 String 유형입니다. 따라서 둘 다 String으로 변환한 다음 비교해야 합니다.result._id.toString()===character._id.toString()돌아올 것이다 true 9 기록 삭제
Mongoose에는 레코드를 삭제할 3개의 레코드가 있습니다.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MarioCharSchema = new Schema({
name: String,
weight: Number
})
const MarioChar = mongoose.model('mariochar', MarioCharSchema)
module.exports = MarioChar;
// Now we can do the following
// var myChar = new MarioChar({ name: "Rayan", weight: 100 });
Mocha는 테스트 프레임워크입니다.
응용 프로그램 내에서 수행하는 데 사용합니다.
모든 것이 올바르게 작동하는지 확인하려면
먼저 모카를 설치하십시오
npm install mocha --save.테스트 스크립트
demo_test.js를 폴더/test에 보관합니다.데모_테스트.js
const mocha = require('mocha');
const assert = require('assert');
describe('Some demo tests', function(){
//Create tests
it('adds two numbers together', function(){
assert(2+3===5)
})
})
test에서 mocha 속성을 package.json로 설정합니다.그리고 실행
npm run test 5 MongoDB에 데이터 저장
const mocha = require('mocha');
const assert = require('assert');
const MarioChar = require('../models/mariochar');
describe('Some demo tests', function(){
//Create tests
it('Saves a record to the database', function(done){
var character = new MarioChar({
name: "Mario",
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
})
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
위의 함수는 character를 데이터베이스에 저장합니다.character.isNew는 객체가 생성되었지만 데이터베이스에 없는 경우 true를 반환합니다.
개체가 데이터베이스에서 발견되면 false를 반환합니다.save는 비동기 함수이므로 다음 테스트를 수행하려면 done 메서드를 통해 언제 완료되는지 명시적으로 알려야 합니다.
mogoose 자체 promise를 사용하는 대신 ES6 promise 사용
const mongoose = require('mongoose');
// Using ES6 promise instead mogoose's promise
mongoose.Promise = global.Promise
// Connect to mongodb
mongoose.connect('mongodb://localhost/testaroo');
mongoose.connection.once('open', function(){
...
}).on('error', function(error){
...
})
이 시점에서 연결이 설정되기 전에도 테스트가 실행되고 있습니다.
그렇게 하려면 연결 코드를 안에 넣어야 합니다before.
before(function(done){
mongoose.connect('mongodb://localhost/testaroo');
mongoose.connection.once('open', function(){
console.log('Conneciton is made');
done();
}).on('error', function(error){
console.log('Connection error', error);
})
})
연결이 설정될 때 명시적으로 알려주는 데 done을 사용했습니다.
6 컬렉션 삭제
컬렉션을 삭제하려면:mongoose.connection.collections.mariochars.drop()우리는 mariochars가 아니라 mariochar (복수화)를 쓰고 있지만 컬렉션을 mariochar로 선언했습니다. 이것이 mongodb가 작동하는 방식입니다.
한 테스트의 결과가 다른 테스트에 영향을 미치지 않도록 모든 테스트 전에 컬렉션을 삭제하려면 beforeEach
const mongoose = require('mongoose');mongoose.Promise = global.Promise
before(function(done){
// Connect to mongodb
...
})
beforeEach(function(done){
mongoose.connection.collections.mariochars.drop()
done()
})
7 기록 찾기
검색을 위해 모델에 find 또는 findOne 방법을 사용할 수 있습니다.
MarioChar.findOne({ name: "Mario"}).then(result => {
...
})
이 코드는 name==="Mario"인 첫 번째 일치 항목을 찾습니다.
우리의finding_test.js 파일은
const assert = require('assert');
const MarioChar = require('../models/mariochar');
describe('Some demo tests', function(){
beforeEach(function(done){
var character = new MarioChar({
name: "Mario",
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
})
//Create tests
it('Finding a record form the database', function(done){
MarioChar.findOne({ name: "Mario"}).then(result => {
assert(result.name === "Mario")
done();
})
})
})
8 개체 ID
컬렉션에서 ID별로 데이터를 검색하려면:
MarioChar.findOne({ _id: character._id }).then(result => {
assert(result._id === character._id)
done();
})
그러나 위의 코드는 다음과 같이 작동하지 않습니다.result._id===character._id는 false를 다음과 같이 반환합니다.result._id는 ObjectID 유형이고 character._id는 String 유형입니다. 따라서 둘 다 String으로 변환한 다음 비교해야 합니다.result._id.toString()===character._id.toString()돌아올 것이다 true 9 기록 삭제
Mongoose에는 레코드를 삭제할 3개의 레코드가 있습니다.
const mocha = require('mocha');
const assert = require('assert');
const MarioChar = require('../models/mariochar');
describe('Some demo tests', function(){
//Create tests
it('Saves a record to the database', function(done){
var character = new MarioChar({
name: "Mario",
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
})
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
const mongoose = require('mongoose');
// Using ES6 promise instead mogoose's promise
mongoose.Promise = global.Promise
// Connect to mongodb
mongoose.connect('mongodb://localhost/testaroo');
mongoose.connection.once('open', function(){
...
}).on('error', function(error){
...
})
before(function(done){
mongoose.connect('mongodb://localhost/testaroo');
mongoose.connection.once('open', function(){
console.log('Conneciton is made');
done();
}).on('error', function(error){
console.log('Connection error', error);
})
})
컬렉션을 삭제하려면:
mongoose.connection.collections.mariochars.drop()우리는 mariochars가 아니라 mariochar (복수화)를 쓰고 있지만 컬렉션을 mariochar로 선언했습니다. 이것이 mongodb가 작동하는 방식입니다.한 테스트의 결과가 다른 테스트에 영향을 미치지 않도록 모든 테스트 전에 컬렉션을 삭제하려면
beforeEachconst mongoose = require('mongoose');mongoose.Promise = global.Promise
before(function(done){
// Connect to mongodb
...
})
beforeEach(function(done){
mongoose.connection.collections.mariochars.drop()
done()
})
7 기록 찾기
검색을 위해 모델에 find 또는 findOne 방법을 사용할 수 있습니다.
MarioChar.findOne({ name: "Mario"}).then(result => {
...
})
이 코드는 name==="Mario"인 첫 번째 일치 항목을 찾습니다.
우리의finding_test.js 파일은
const assert = require('assert');
const MarioChar = require('../models/mariochar');
describe('Some demo tests', function(){
beforeEach(function(done){
var character = new MarioChar({
name: "Mario",
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
})
//Create tests
it('Finding a record form the database', function(done){
MarioChar.findOne({ name: "Mario"}).then(result => {
assert(result.name === "Mario")
done();
})
})
})
8 개체 ID
컬렉션에서 ID별로 데이터를 검색하려면:
MarioChar.findOne({ _id: character._id }).then(result => {
assert(result._id === character._id)
done();
})
그러나 위의 코드는 다음과 같이 작동하지 않습니다.result._id===character._id는 false를 다음과 같이 반환합니다.result._id는 ObjectID 유형이고 character._id는 String 유형입니다. 따라서 둘 다 String으로 변환한 다음 비교해야 합니다.result._id.toString()===character._id.toString()돌아올 것이다 true 9 기록 삭제
Mongoose에는 레코드를 삭제할 3개의 레코드가 있습니다.
MarioChar.findOne({ name: "Mario"}).then(result => {
...
})
const assert = require('assert');
const MarioChar = require('../models/mariochar');
describe('Some demo tests', function(){
beforeEach(function(done){
var character = new MarioChar({
name: "Mario",
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
})
//Create tests
it('Finding a record form the database', function(done){
MarioChar.findOne({ name: "Mario"}).then(result => {
assert(result.name === "Mario")
done();
})
})
})
컬렉션에서 ID별로 데이터를 검색하려면:
MarioChar.findOne({ _id: character._id }).then(result => {
assert(result._id === character._id)
done();
})
그러나 위의 코드는 다음과 같이 작동하지 않습니다.
result._id===character._id는 false를 다음과 같이 반환합니다.result._id는 ObjectID 유형이고 character._id는 String 유형입니다. 따라서 둘 다 String으로 변환한 다음 비교해야 합니다.result._id.toString()===character._id.toString()돌아올 것이다 true 9 기록 삭제
Mongoose에는 레코드를 삭제할 3개의 레코드가 있습니다.
char.remove() MarioChar.remove() 대괄호 안에 옵션을 전달할 것입니다. MarioChar.findOneAndRemove() 대괄호 안에 옵션을 전달할 것입니다. findOneAndRemove() 사용MarioChar.findOneAndRemove({ name:"Mario" }).then(function(){
MarioChar.findOne({ name:"Mario" })
})
10 기록 갱신
다양한 몽구스 방법
// Saving the data
character = new MarioChar({
name: "Mario",
weight: 60
})
character.save().then(function(){
...
})
// Updating the data
MarioChar.findOneAndUpdate({ name:"Mario"}, { name:"new_name"}).then(function(){
MarioChar.findOne({ name:"Mario" }).then(result => {
...
})
})
새 변경 사항이 주입되고 전체 개체를 덮어쓰지 않습니다. 이 업데이트는 개체에 다음과 같은 결과를 가져옵니다.
{ name: "new_name", weight: 100 } 뿐만 아니라 { name: "new_name" } 11 관계형 데이터
Author(name, age, books)와 Book(title, pages)이 두 관계라고 가정합니다.
다음과 같은 방법으로 MongoDB에서 구성합니다.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookSchema = new Schema({
title: String,
pages: Number
});
const AuthorSchema = new Schema({
name: String,
age: Number,
books: [BookSchema]
})
const Author = mongoose.model('author', AuthorSchema);
module.exports = Author;
books: [BookSchema]는 books 속성이 배열 요소가 BookSchema 형식이 될 배열임을 알려줍니다.
12 문서 중첩
const mongoose = require('mongoose');
const assert = require('assert')
const Author = require('../models/author');
describe('Nesting Documents', function(){
//Create tests
it('Create an author with sub-documents', function(done){
var pat = new Author({
name: 'Patrick Ruffus',
books:[{title:'Name of the wind', pages: 400}]
});
pat.save().then(function(){
Author.findOne({name:'Patrick Ruffus'}).then(function(record){
assert(record.books.length === 1);
done();
})
})
})
it('Add a book to an existing author', function(done){
var rus = new Author({
name: 'Ruskin Bond',
books:[{title:'The eyes have it', pages: 400}]
});
rus.save().then(function(){
Author.findOne({name:'Ruskin Bond'}).then(function(record){
record.books.push({title:"7 husband", pages:200});
record.save().then(function(){
Author.findOne({ name: 'Ruskin Bond' }).then(function(record){
assert(record.books.length===2);
done();
})
})
})
})
})
})
Reference
이 문제에 관하여(몽고DB 소개), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/rittwickbhabak/introduction-to-mongodb-318i
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookSchema = new Schema({
title: String,
pages: Number
});
const AuthorSchema = new Schema({
name: String,
age: Number,
books: [BookSchema]
})
const Author = mongoose.model('author', AuthorSchema);
module.exports = Author;
const mongoose = require('mongoose');
const assert = require('assert')
const Author = require('../models/author');
describe('Nesting Documents', function(){
//Create tests
it('Create an author with sub-documents', function(done){
var pat = new Author({
name: 'Patrick Ruffus',
books:[{title:'Name of the wind', pages: 400}]
});
pat.save().then(function(){
Author.findOne({name:'Patrick Ruffus'}).then(function(record){
assert(record.books.length === 1);
done();
})
})
})
it('Add a book to an existing author', function(done){
var rus = new Author({
name: 'Ruskin Bond',
books:[{title:'The eyes have it', pages: 400}]
});
rus.save().then(function(){
Author.findOne({name:'Ruskin Bond'}).then(function(record){
record.books.push({title:"7 husband", pages:200});
record.save().then(function(){
Author.findOne({ name: 'Ruskin Bond' }).then(function(record){
assert(record.books.length===2);
done();
})
})
})
})
})
})
Reference
이 문제에 관하여(몽고DB 소개), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/rittwickbhabak/introduction-to-mongodb-318i텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)