【发布时间】:2020-08-03 07:29:58
【问题描述】:
我将以下应用程序保存到内存存储库中。我连接了本地 mongodb,但将发布的数据保存到 mongodb 时遇到问题。
当应用程序保存到内存时,它工作得很好,我可以使用 curl 显示保存在那里的不同事件的数组。我现在想让它保存到我的数据库中,这样我就可以使用保存的数据,但我找不到任何明确的教程
有人可以建议应该怎么做吗?
MongoDB架构:
import { mongoose } from '././http'
const CompetitionSchema = new Schema({
id: String,
place: String,
time: String,
subscriptions: [],
date: new Date(),
cost: {
currency: String,
amount: Number,
},
})
export const CompetitionModel = mongoose.model(
'CompetitionModel',
CompetitionSchema,
)
export default CompetitionSchema
http:
export const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/CompetitionEvent')
const db = mongoose.connection
db.on('error', console.error.bind(console, 'An error has occured: '))
db.once('open', function () {
console.log('Connected to Mongodb')
})
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.get('/events', (_req: any, res: any) => {
res.send(eventApplication.getAll())
})
app.post('/event', async (req: any, res: any) => {
await eventApplication.createAnEvent(req.body)
res.json({
success: true,
})
})
app.listen(8000)
在内存和 mongodb 存储库中
export interface EventRepositoryInterface {
// will require ansyc call will have return promise of all below - refactor needed
save: (event: CompetitionEvent) => void
getById: (id: string) => CompetitionEvent | undefined
getAll: () => CompetitionEvent[]
}
export class InMemoryEventRepository implements EventRepositoryInterface {
constructor(private events: CompetitionEvent[] = []) {}
public save = (event: CompetitionEvent) =>
(this.events = [...this.events, event])
public getById = (id: string) => this.events.find((e) => e.id === id)
public getAll = () => this.events
}
export class MongoCompetitionEventRepository
implements EventRepositoryInterface {
constructor(private events: CompetitionEvent[] = []) {}
//here event should go to DB and NOT in the array memory
public save = (event: CompetitionEvent) =>
(this.events = [...this.events, event])
public getById = (id: string) => this.events.find((e) => e.id === id)
public getAll = () => this.events
}
如有遗漏请告诉我,我会修改帖子
【问题讨论】:
标签: node.js mongodb typescript mongoose