javascript 节点js + mongoose
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 节点js + mongoose相关的知识,希望对你有一定的参考价值。
require('dotenv').config()
const createError = require('http-errors')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('morgan')
const mongoose = require('mongoose')
const indexRouter = require('./routes/index')
const app = express()
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use('/', indexRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404))
})
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
// render the error page
res.status(err.status || 500)
res.render('error')
})
//mongodb connection
mongoose.connect('mongodb://'+process.env.DB_USER+':'+process.env.DB_PWD+'@'+process.env.DB_HOST+'/'+process.env.DB_NAME , {
useCreateIndex: true,
useNewUrlParser: true
})
const db = mongoose.connection
module.exports = app
const express = require('express')
const router = express.Router()
const Article = require('../models/article')
const Category = require('../models/category')
/* GET home page. */
router.get('/', async function(req, res) {
let articles = await Article.find().populate('category').sort('-date')
console.log(articles);
res.render('index', {articles: articles})
})
// manager page
router.get('/manage', async function(req, res) {
let articles = await Article.find().populate('category').sort('-date')
console.log(articles);
res.render('manage', {articles: articles})
})
// writing page
router.get('/writePost', async function(req,res,next){
let categories = await Category.find()
res.render('writePost',{categories:categories})
})
// edit page
router.get('/edit_post/:id', async function(req, res) {
let article = await Article.findById(req.params.id)
let categories = await Category.find()
res.render('editPost',{article:article,categories:categories})
})
// edit db
router.post('/updatePost', async function(req,res,next){
let article = await Article.findById(req.body._id)
article.title = req.body.title
article.description = req.body.description
article.category = req.body.category
article.save()
res.redirect('/manage')
})
// database handler
router.post('/new_post', function(req, res) {
let article = new Article
article.title = req.body.title
article.description = req.body.description
article.date = Date()
article.category = req.body.category
article.save()
res.redirect('/')
})
router.post('/new_category', function(req, res) {
let category = new Category
category.name = req.body.name
category.save(function(err, category) {
if (err) console.log(err)
res.send(category)
})
})
router.post('/delete_post', async function(req,res,next){
let articleId = req.body.articleId
let article = await Article.findById(articleId)
article.remove()
res.send(article)
})
module.exports = router
const mongoose = require('mongoose')
const ArticleSchema = new mongoose.Schema({
title: {
type: String,
unique: true
},
description: String,
date: Date,
thumbnail: String,
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category'
}
})
const Article = mongoose.model('Article', ArticleSchema)
module.exports = Article
const mongoose = require('mongoose')
const CategorySchema = new mongoose.Schema({
name: String
})
const Category = mongoose.model('Category', CategorySchema)
module.exports = Category
extends layout
block content
a(href='/manage')
button.btn_manage MANAGE
a(href='/writePost')
button.btn_new NEW
div.title
h1 ARTICLES
div.articles
each article in articles
div.article
h1= article.title
p= article.description
h4= article.category.name
div.btnArea
extends layout
block content
a(href='/')
button.btn_manage BACK
div.articles
h1 Article writer
form(method="POST" action="/new_post")
h4 title
input(type="text" name="title")
h4 description
input(type="text" name="description")
h4 category
select(name="category")
each category in categories
option(value=category._id)= category.name
input(type="submit")
block scripts
extends layout
block content
a(href='/')
button.btn_manage BACK
div.title
h1 ARTICLES
div.articles
each article in articles
div.article(data-id=article._id)
h1= article.title
p= article.category.name
p= article.description
div.btnArea
a(href='/edit_post/'+article._id).smallBtn.editBtn edit
a(href='#').smallBtn.deleteBtn delete
block scripts
script(src='js/manage.js')
extends layout
block content
a(href='/')
button.btn_manage BACK
div.articles
h1 Article writer
form(method="POST" action="/updatePost")
input(type="hidden" name="_id" value=article._id)
h4 title
input(type="text" name="title" value=article.title)
h4 description
input(type="text" name="description" value=article.description)
h4 category
select(name="category")
each category in categories
option(value=category._id selected=(category._id.toString()==article.category ? true : false))= category.name
input(type="submit")
block scripts
$(function() {
$('.deleteBtn').on('click', function(e) {
e.preventDefault()
//get article id from the closest object that has the class
let articleId = $(this).closest('.article').attr('data-id')
$.ajax({
url: '/delete_post',
type: 'POST',
data: {
articleId: articleId
},
success: function(data) {
if(data != undefined){
$('.article[data-id='+articleId+']').remove()
console.log('deleted');
}else{
console.log('failed');
}
},
error: function(request, status, error) {
console.log('code: ' + request.status + ' error: ' + error)
}
})
})
})
以上是关于javascript 节点js + mongoose的主要内容,如果未能解决你的问题,请参考以下文章
带有固定节点的 Javascript cytoscape.js 自动布局