mongod
, mongo
순서대로 입력.mongo
명령어 실행 시 나오는 url
을 받아와야 함. npm i mongoose // mongoose 설치
import mongoose from "mongoose"; // import
// terminal 창에서 mongo 명령 실행 시 나오는 "url/내가 설정할 폴더명" 넣기
mongoose.connect("url/폴더명"); // string으로 된 Database 를 요청
// mongoose 연결 확인
// on 은 여러 번 발생 가능
mongoose.connection.on("error", (error) => console.log("Error!", error));
// once 는 한 번만 발생 가능
mongoose.connection.once("open", () => console.log("Connected!"));
import mongoose from "mongoose";
// Schema 설정
const contentsSchema = new mongoose.Schema({
title: { type: String, required: true },
description: String, // String 은 {type: String} 을 간결하게 나타낸 것임
hashtags: [{ type: String }],
views: { type: Number, required: true },
});
// 미들웨어 위치
// Model 생성
// 여기서 mongoose.model()은 contentsSchema의 복사본이라 보면 됨
const Contents = mongoose.model("Contents", contentsSchema);
// Model export
export default Contents
https://mongoosejs.com/docs/middleware.html
// 미들웨어의 형태
schema.pre("save", async function(){});
// 예시 - save 전에 console.log()가 실행됨
contentsSchema.pre("save", async function(){
console.log(this); // this 는 저장하려는 정보를 나타냄
});
const contents = new Contents({
title, // title: title
description, // description: description
hashtags: hashtags.split(",").map((text)=>`#${text}`),
views: 0,
});
await contents.save();
await Contents.create({
title,
description,
hashtags: hashtags.split(",").map((text)=>`#${text}`),
views: 0,
});