const { Schema } = require('mongoose');
// convention
const PostSchema = new Schema({
title: String,
content: String,
}, {
timestamps: true,
});
const mongoose = require('mongoose');
const PostSchema = require('./schemas/board')
exports.Post = mongoose.model('Post', PostSchema);
// module.exports = mongoose.model('Post', PostSchema);
'Post'
: 모델의 이름const mongoose = require('mongoose');
const { Post } = require('./models');
mongoose.connect('DBURL');
2.2.3의 코드에서 연결
async function create() {
const created = await Post.create({
title: 'first title',
content: 'first article',
});
// object array 전달로 복수의 document를 생성할 수 있다.
const multipleCreated = await Post.create([
item1,
item2
]);
}
async function read() {
const postLists = await Post.find(query);
const onePost = await Post.findOne(query);
const postById = await Post.findById(id);
}
async function update() {
// update~는 쿼리의 결과를 반환
const updateResult = await Post.updateOne(query, {
...
});
const updateResults = await Post.updateMany(query, {
...
});
// find~ 함수들은 검색된 document를 업데이트하여 반환해 줌
const updateById = await Post.findByIdAndUpdate(id, {
...
});
const onePost = await Post.findOneAndUpdate(query, {
...
});
}
async function del() {
const deleteResult = awiat Post.deleteOne(query);
const deleteResults = await Post.deleteMany(query);
const onePost = await Post.findOneAndDelete(query);
const postById = await Post.findByIdAndDelete(id);
}
const Post = new Schema({
...
user: {
type: Schema.Types.ObjectId,
ref: 'User' // 여기에 입력한 값을 기준으로 populate한다.
},
comments: [{
type: Schema.Types.ObjectId,
ref: 'Comment'
}],
});
// 적용하고자 하는 파일에 추가
const post = await Post.find().populate(['user', 'comments']);
ref: ''
: 앞에서 model을 선언할 때 사용한 name과 같음Mongoose.connect
를 위치한다.