node.js博客项目开发手记

2020-06-17 07:07:46易采站长站整理

User.findOne({
username:username
}).then(function(result){

});

// 根据用户ID查询数据
User.findById(id).then(function(user){

});

// 根据ID删除数据
User.remove({
_id: id
}).then(function(){

});

// 修改数据
User.update({
_id: id
},{
username: name
}).then(function(){
});

数据分页管理

两个重要方法

limit(Number): 限制获取的数据条数

skip(Number): 忽略数据的条数 前number条

忽略条数:(当前页 – 1) * 每页显示的条数


// 接收传过来的page
let query_page = Number(req.query.page) || 1;
query_page = Math.max(query_page, 1); // 限制最小为1
query_page = Math.min(Math.ceil(count / limit), query_page); // 限制最大值 count/limit向上取整

var cur_page = query_page; // 当前页
var limit = 10; // 每页显示的条数
var skip = (cur_page - 1) * limit; //忽略的条数

User.find().limit(limit).skip(skip).then(function(users){
...
// 将当前页 page 传给页面
// 将最大页码 maxPage 传给页面
});

文章的表结构


// 对于content.js
var mongoose = require('mongoose');
var contentSch = require('../schemas/contentSch');

module.exports = mongoose.model('Content',contentSch);

// contentSch.js
module.exports = new mongoose.Schema({

// 关联字段 - 分类的id
category:{
// 类型
type:mongoose.Schema.Types.ObjectId,
// 引用
ref:'Category'
},

// 内容标题
title: String,

// 简介
description:{
type: String,
default: ''
},

// 内容
content:{
type:String,
default:''
}
});

// 文章查询时关联category字段
Content.find().populate('category').then(contents => {
// 那么通过这样的方式,我们就可以找到Content表中的
// 关联信息 content.category.category_name
});

MarkDown语法高亮

在HTML中直接使用


<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>

<script src="https://cdn.bootcss.com/marked/0.3.17/marked.min.js"></script>

// marked相关配置
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false,
highlight: function (code) {
return hljs.highlightAuto(code).value;