Mongoose
- MongoDB ODM(Object Document Mapper)
예시
import Mongoose from "mongoose";
export async function connectDB() {
return Mongoose.connect(url, options);
}
export function useVirtualId(schema) {
schema.virtual('id').get(function() {
return this._id.toString(); // this._id는 object이므로 toString해준다.
});
schema.set("toJSON", {virtuals : true}); // id정보 json에 포함
schema.set("toObject", {virtuals : true}); // console.log에 가상의 필드 추가
}
import Mongoose from "mongoose";
import {useVirtualId} from "database.js 경로";
const userSchema = new Mongoose.Schema({
username : {type : String, required : true},
name : {type : String, required : true},
email : {type : String, required : true},
password : {type : String, required : true},
url : String
});
useVirtualId(userSchema);
const User = Mongoose.model("User", userSchema); // User의 collection을 userschema와 연결
export async function createUser(user) {
return new User(user).save().then(data => data.id); // data안에 있는 id를 전달
}
export async function findByUsername(username) {
return User.findOne({username});
}
export async function findById(id) {
return User.findById({id});
}
export async function updateUser(id, email) {
return User.findByIdAndUpdate(id, {email}, {returnOriginal : false}); // update된 정보를 return
}
export async function removeUser(id) {
return User.findByIdAndDelete(id);
}
참고자료