models 폴더의 schema.js
// ./models/schema.js const mongoose = require('mongoose'); const { Schema } = mongoose; const ChatSchema = new Schema({ userId: { type: String }, text: { type: String, createdAt: { type: Date, default: Date.now, immutable: true }}, }, { versionKey: false }) module.exports = mongoose.model('Chat', ChatSchema);
module.exports = mongoose.model('Chat', ChatSchema);
마지막줄로 등록한 모델을 외부에서 사용할 수 있게끔 export 해준다.
// src/index.js const Chat = require('./models/schema'); socket.on('SEND_MESSAGE', function(data) { io.emit('SEND_MESSAGE', data); let chat = new Chat({text: data.message}); chat.save(function (err, data) { if(err) { console.log('error'); } console.log('message is inserted'); }); })
src폴더의 index.js에서 사용하려면
const Chat = require('./models/sample/schema');
1. require()은 module.exports를 리턴받기 때문에 Schema를 내보낸 경로를 require 해준다.
2. 새로운 document를 생성하고,
3. mongoose의 save() 메서드를 사용해 db에 저장한다. (save 메서드는 promise객체를 반환한다)