Last active
January 6, 2021 03:15
-
-
Save aramis-it/1f2fde4de3db051f62a62d9af0de426f to your computer and use it in GitHub Desktop.
mongodb expressjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mongoose from 'mongoose'; | |
mongoose.connect('mongodb://localhost:27017/mongotest', { useNewUrlParser: true }); | |
const db = mongoose.connection; | |
db.on('error', console.error.bind(console, 'connection error:')); | |
db.once('open', function () { | |
// we're connected! | |
console.log("MongoDB connected"); | |
}); | |
interface kitten extends mongoose.Document { | |
name: string; | |
} | |
const kittySchema = new mongoose.Schema({ | |
name: String | |
}, { strict: false }); | |
const Kitten = mongoose.model<kitten>('Kitten', kittySchema); | |
app.post('/mpost', function (req, res) { | |
const record = new Kitten(req.body); | |
console.log('record:', record) | |
record.save(function (err) { | |
if (err) return console.error(err); | |
}); | |
res.send("success mongo") | |
}) | |
app.get('/findAll', function (req, res) { | |
let result = Kitten.find(function (err, kittens) { | |
if (err) return console.error(err); | |
console.log('result', kittens) | |
return kittens | |
}) | |
console.log('findAll', result) | |
res.send({ result }) | |
}) | |
app.get('/findById/:id', function (req, res) { | |
let result = Kitten.findById(req.params.id) | |
console.log('result', result) | |
res.send("ok") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment