항해99/챕터3 주특기 Node.js
항해 25일) Node.js- 몽고디비-로보3티에서 직접 문서추가, 수정하기 mongoDB, mongoose, Robo3T
뽀짝코딩
2022. 2. 3. 10:52
728x90
몽고DB에 데이터를 삽입하는 방법
몽고DB에 데이터를 삽입하는 명령어는 save()이며, 기본적인 형식은 다음과 같다.
db.콜렉션이름.save( 삽입할 데이터의 JSON );
기본적으로 몽고DB는 JSON 형태의 문서를 바탕으로 데이터를 저장 및 운영하기 때문에 save() 명령의 매개변수는 JSON 형식이다. 다음의 명령어를 실행해 보자.
몽고DB에서는 기본적으로 JSON 형태의 문서를 사용한다
db.posts.save({ password: 'asdf' });
콜렉션- posts
문서- password
필드 값- 'asdf'
단, 이렇게 하면 새롭게 _id가 생성된다.
문서 업데이트, 삭제
업데이트, 삭제는 마우스 오른쪽을 클릭해서 할수 있다.
1). 업데이트
"password" : "asdf", 추가함
password문서에 'asdf' 필드값이 추가되었다.
2). 삭제
****공부하기*****
import mongoose from 'mongoose'
import { commentSchema } from './comment.js'
const postSchema = new mongoose.Schema({
text: {
type: String,
require: true
},
userId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
created_at: {
type: Date,
default: Date.now
},
// Subdocument can hold up to 16MB, which is about 68,000 100-character comments
// Thus it's safe to use here
comments: [commentSchema],
// count the number of liked users by implementing a method
likedUsers: {
type: [mongoose.Schema.Types.ObjectId],
default: [],
ref: 'User'
}
})
export default mongoose.model('Post', postSchema)
mongoose.Schema.Types.ObjectId - 관련블로거글
https://devlog-h.tistory.com/27
깃헙-항해 2기13조-주특기미니프로젝트
https://github.com/seungbin0508/99naru/tree/main/backend
반응형