【问题标题】:Typescript and mongoose: saving to database打字稿和猫鼬:保存到数据库
【发布时间】: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


    【解决方案1】:

    您在这里所做的是连接到本地 MongoDB,现在您必须登录到 MongoDB 网站,即here,登录后首先要做的是创建一个用户来访问 db/collections,点击数据库访问,添加用户,使用认证模式作为密码创建用户,接下来你必须将你的IP地址列入白名单,点击网络访问并添加您的IP地址或0.0.0.0/0(这基本上意味着包括您在内的所有/任何IP地址都可以访问此数据库),之后您必须创建一个新数据库,在数据库内您必须创建集合,做点击ClustersCollection并从那里创建你的数据库,最后完成所有你需要连接到数据库的操作,点击Clusters,Connect 并选择 Connect ApplicationConnect using MongoDB Compass 选项,这将为您提供连接 URL 如下所示:-


    mongodb+srv://<username>:<password>@cluster0-gd3lq.mongodb.net/test


    对于 MongoDB 指南针 选项


    mongodb+srv://<username>:<password>@cluster0-gd3lq.mongodb.net/<dbname>?retryWrites=true&w=majority


    像这里的 Connect Application 选项一样,您将不得不更改 <username>:<password> 与用于在 Database Access 中创建用户的用户名和密码也更改<dbname> 与您的实际数据库名称。 如果您有 mongoose.connect('mongodb://localhost:27017/CompetitionEvent'),则必须将其替换为您的连接 URL。

    参考:-

    【讨论】:

    • 谢谢,但我想故意将它保存在我的本地机器上。不要在线存储任何数据。我的问题更多是如何让我的 MongoCompetitionEventRepository 保存到本地数据库而不是内存:)
    猜你喜欢
    • 2020-11-14
    • 2020-01-26
    • 2017-01-20
    • 2016-02-05
    • 2020-05-11
    • 2016-04-01
    • 1970-01-01
    • 2021-10-05
    • 2021-03-13
    相关资源
    最近更新 更多