简体   繁体   中英

Typescript and mongoose: saving to database

I have the following app saving into memory repo. I connected a local mongodb but I have issues saving the posted data into mongodb. When the app is saving to the memory it works just fine and I can use curl to display the array of different event saved there. I now would like to make it save into my DB so I can then work with the data saved and I couldn't find any clear tutorial on that Can someone advice how it should be done?
Mongodb schema:

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)

in memory and mongodb repository


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
}

Please let me know if something is missing I'll edit the post

what you have done here is connected to the local MongoDB now you will have to login to the MongoDB website ie, here , after logging in the very first thing to do is create a user to access the db/collections, click on Database Access , add a user, use the authentication mode as password to create the user, next you will have to whitelist your IP address to do that click on Network Access and add either your IP Address or 0.0.0.0/0 (which basically means all/any IP address including yours can access this DB), after that you will have to create a new DB, inside the DB you will have to create collections, to do this click on Clusters , Collection and create your db from there, finally to complete it all you will need to connect to the DB, for this click on Clusters , Connect and choose either the Connect Application o r the Connect using MongoDB Compass option this will give you the connection URL looking like this:-


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


for the MongoDB compass option


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


and like this for Connect Application option over here you will have to change the <username>:<password> with the username and password used to create the user in Database Access also change the <dbname> with your actual DB name. In your case where you have mongoose.connect('mongodb://localhost:27017/CompetitionEvent') you have to replace it with your connection URL.

References:-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM