使用Node.js开发App的步骤
-
创建项目目录
mkdir myapp cd myapp # 合并以上两步骤 mkdir myapp && cd myapp
-
初始化
npm init --yes //目的:创建package.json文件,该文件记录了项目项目信息及项目中所有使用的模块。
-
创建项目结构
myapp - views - public - routes - package.json - package-lock.json - app.js
-
安装模块
npm install express
-
引入模块
const express = require('express')
-
写需求
.....
网站根目录
-
根目录
VS用户根目录
\ vs ~
查看当前位置: pwd
项目根目录:访问权限设置为公开的、任何人都可以访问的。
public目录
定义
Public 目录是Node.js中存放网站静态文件的目录。静态文件包括:
- 图片
- css文件
- js文件
- 字体文件
mkdir public && cd public
mkdir css js images
Public : 公共的、共同的、公开
express框架
- 框架的核心是构造函数express()
- Express()** 构造函数用于创建一个APP实例(服务器类型的app)**
- express是基于Node.js平台
- Node.js平台是运行js文件的。
- Node.js项目目录
- index.js app.js server.js
- views
- html视图模版
- ejs视图引擎
- html视图模版
- public
- 引入静态资源
- 普通项目目录
- index.html
- css
- style.css
- js
- Script.js
知识点1:express.static()
定义
语法
返回值
示例
知识点2:创建数据库
方案1:创建本地mongodb数据库
-
启动mongodb数据库
# window系统 服务 => 右键 => 启动 # Mac OS brew services start mongodb/brew/mongodb-community
-
连接数据库(怎么和数据库通信?)
- 可以使用可视化软件Compass
- 非可视化软件:mongosh
mongosh "mongodb://localhost:27017"
-
创建数据库: zhangsanblog
使用compass手动创建
-
使用mongosh手动创建
use zhangsanblog
-
创建数据库用户
-
语法
Db.createUser({ user: 'zhangsan', pwd: '123456', roles: [{ role:"readWrite",db:"config"},"clusterAdmin"], roles: ["readWrite"] })
-
方案2:创建云数据库
- 登录Atlas账户
- 创建数据库 : zhangsanblog
- 创建用户: zhangsan Zxcvbn123456
知识点3:连接字符串
定义
连接字符串特指在App开发过程中连接数据库的地址。
语法
"协议://用户名:密码@数据库地址/数据库名"
云数据库的连接字符串
从云数据库复制的连接字符串:
'mongodb+srv://<username>:<password>@zhangsanblog.4t6hj0s.mongodb.net/?retryWrites=true&w=majority'
用你的用户名和密码替换<username>和<password>
'mongodb+srv://zhaolusiblong:202303013@zhaolusiblong.towdlc9.mongodb.net/?retryWrites=true&w=majority'
本地数据库的连接字符串
"mongodb://zhangsan:123456@127.0.0.1:27107/zhangsanblog"
"mongodb://zhangsan:123456@localhost:27107/zhangsanblog"
知识点4:Node和MongoDB的通信
通信方式有两种:
- Mongodb模块:
- mongodb模块是Node.js原生提供的与mongoDB数据库通信的API。
- Mongoose模块:
- 是第三方提供的在Node平台与MongoDB数据库通信的方式。
- Mongoose是一个库。
- 库:就是函数的集合。
- Mongoose库包裹Node API。
知识点5:使用Mongoose模块连接数据库
const mongoose = require('mongoose')
mongoose.connect(uri)
.then((result) => {
console.log('数据库已经连接')
})
.catch( err => console.log(err))
mongoose是什么?
- 核心:mongoose()构造函数
- mongoose是一个ODM(对象数据模型)。(object Data Model)
- 使用js对象的语法来映射mongoose数据库种的表和document
- collection:数据库中的表;
- document:数据中的文档;
打印mongoose
const mongoose = require('mongoose')
引入mongoose模块会自动创建mongoose实例对象。
- mongoose是一个对象
- Mongoose.connections 属性
- mongoose.Schema :构造函数
- Mongoose.model: 函数
Mongoose {
connections: [
NativeConnection {
base: [Circular *1],
collections: {},
models: {},
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
plugins: [],
id: 0,
_queue: [],
_listening: false
}
],
nextConnectionId: 1,
models: {},
events: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
},
__driver: {
Collection: [Function: NativeCollection],
Connection: [Function: NativeConnection] { STATES: [Object: null prototype] }
},
options: {
pluralization: true,
autoIndex: true,
autoCreate: true,
[Symbol(mongoose:default)]: true
},
_pluralize: [Function: pluralize],
Schema: [Function: Schema] {
reserved: [Object: null prototype] {
validate: 1,
toObject: 1,
save: 1,
remove: 1,
populated: 1,
isNew: 1,
isModified: 1,
init: 1,
get: 1,
errors: 1,
collection: 1,
removeListener: 1,
listeners: 1,
emit: 1,
prototype: 1
},
Types: {
String: [Function],
Number: [Function],
Boolean: [Function],
DocumentArray: [Function],
Subdocument: [Function],
Array: [Function],
Buffer: [Function],
Date: [Function],
ObjectId: [Function],
Mixed: [Function],
Decimal: [Function],
Decimal128: [Function],
Map: [Function],
UUID: [Function],
Oid: [Function],
Object: [Function],
Bool: [Function],
ObjectID: [Function]
},
ObjectId: [Function: ObjectId] {
schemaName: 'ObjectId',
defaultOptions: {},
get: [Function (anonymous)],
set: [Function: set],
_checkRequired: [Function (anonymous)],
_cast: [Function: castObjectId],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
checkRequired: [Function (anonymous)]
}
},
model: [Function (anonymous)],
plugins: [
[ [Function: removeSubdocs], [Object] ],
[ [Function: saveSubdocs], [Object] ],
[ [Function], [Object] ],
[ [Function: trackTransaction], [Object] ],
[ [Function: validateBeforeSave], [Object] ]
],
default: [Circular *1],
mongoose: [Circular *1],
cast: [Function: cast],
STATES: [Object: null prototype] {
'0': 'disconnected',
'1': 'connected',
'2': 'connecting',
'3': 'disconnecting',
'99': 'uninitialized',
disconnected: 0,
connected: 1,
connecting: 2,
disconnecting: 3,
uninitialized: 99
},
setDriver: [Function: setDriver],
set: [Function (anonymous)],
get: [Function (anonymous)],
createConnection: [Function (anonymous)],
connect: [AsyncFunction: connect],
disconnect: [AsyncFunction: disconnect],
startSession: [Function (anonymous)],
pluralize: [Function (anonymous)],
deleteModel: [Function (anonymous)],
modelNames: [Function (anonymous)],
plugin: [Function (anonymous)],
version: '7.0.3',
Mongoose: [Function: Mongoose],
SchemaType: [Function: SchemaType] {
cast: [Function: cast],
set: [Function: set],
get: [Function (anonymous)],
_isRef: [Function (anonymous)],
checkRequired: [Function (anonymous)],
CastError: [class CastError extends MongooseError],
ValidatorError: [class ValidatorError extends MongooseError]
},
SchemaTypes: {
String: [Function: SchemaString] {
schemaName: 'String',
defaultOptions: {},
_cast: [Function: castString],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
get: [Function (anonymous)],
set: [Function: set],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Number: [Function: SchemaNumber] {
get: [Function (anonymous)],
set: [Function: set],
_cast: [Function: castNumber],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
schemaName: 'Number',
defaultOptions: {},
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Boolean: [Function: SchemaBoolean] {
schemaName: 'Boolean',
defaultOptions: {},
_cast: [Function],
set: [Function: set],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)],
'$conditionalHandlers': [Object]
},
DocumentArray: [Function: DocumentArrayPath] {
schemaName: 'DocumentArray',
options: [Object],
defaultOptions: {},
set: [Function: set]
},
Subdocument: [Function: SubdocumentPath] {
defaultOptions: {},
set: [Function: set]
},
Array: [Function: SchemaArray] {
schemaName: 'Array',
options: [Object],
defaultOptions: {},
set: [Function: set],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Buffer: [Function: SchemaBuffer] {
schemaName: 'Buffer',
defaultOptions: {},
_checkRequired: [Function (anonymous)],
set: [Function: set],
checkRequired: [Function (anonymous)]
},
Date: [Function: SchemaDate] {
schemaName: 'Date',
defaultOptions: {},
_cast: [Function: castDate],
set: [Function: set],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
ObjectId: [Function: ObjectId] {
schemaName: 'ObjectId',
defaultOptions: {},
get: [Function (anonymous)],
set: [Function: set],
_checkRequired: [Function (anonymous)],
_cast: [Function: castObjectId],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Mixed: [Function: Mixed] {
schemaName: 'Mixed',
defaultOptions: {},
get: [Function (anonymous)],
set: [Function: set]
},
Decimal: [Function: Decimal128] {
schemaName: 'Decimal128',
defaultOptions: {},
_cast: [Function: castDecimal128],
set: [Function: set],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Decimal128: [Function: Decimal128] {
schemaName: 'Decimal128',
defaultOptions: {},
_cast: [Function: castDecimal128],
set: [Function: set],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Map: [class Map extends SchemaType] {
schemaName: 'Map',
defaultOptions: {}
},
UUID: [Function: SchemaUUID] {
schemaName: 'UUID',
defaultOptions: {},
_cast: [Function (anonymous)],
set: [Function: set],
cast: [Function: cast],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Oid: [Function: ObjectId] {
schemaName: 'ObjectId',
defaultOptions: {},
get: [Function (anonymous)],
set: [Function: set],
_checkRequired: [Function (anonymous)],
_cast: [Function: castObjectId],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Object: [Function: Mixed] {
schemaName: 'Mixed',
defaultOptions: {},
get: [Function (anonymous)],
set: [Function: set]
},
Bool: [Function: SchemaBoolean] {
schemaName: 'Boolean',
defaultOptions: {},
_cast: [Function],
set: [Function: set],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)],
'$conditionalHandlers': [Object]
},
ObjectID: [Function: ObjectId] {
schemaName: 'ObjectId',
defaultOptions: {},
get: [Function (anonymous)],
set: [Function: set],
_checkRequired: [Function (anonymous)],
_cast: [Function: castObjectId],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
checkRequired: [Function (anonymous)]
}
},
VirtualType: [Function: VirtualType],
Types: {
Array: [Function: MongooseArray],
Buffer: [Function: MongooseBuffer] {
pathSymbol: Symbol(mongoose#Buffer#_path),
mixin: [Object],
Binary: [Function]
},
Embedded: [Function: ArraySubdocument] {
_events: undefined,
_eventsCount: 0,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
prependListener: [Function: prependListener],
once: [Function: once],
prependOnceListener: [Function: prependOnceListener],
removeListener: [Function: removeListener],
off: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
rawListeners: [Function: rawListeners],
listenerCount: [Function: listenerCount],
eventNames: [Function: eventNames]
},
Document: [Function: ArraySubdocument] {
_events: undefined,
_eventsCount: 0,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
prependListener: [Function: prependListener],
once: [Function: once],
prependOnceListener: [Function: prependOnceListener],
removeListener: [Function: removeListener],
off: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
rawListeners: [Function: rawListeners],
listenerCount: [Function: listenerCount],
eventNames: [Function: eventNames]
},
DocumentArray: [Function: MongooseDocumentArray],
Decimal128: [class Decimal128 extends BSONValue],
ObjectId: [class ObjectId extends BSONValue] { index: 7107676 },
Map: [class MongooseMap extends Map],
Subdocument: [Function: Subdocument]
},
Query: [Function: Query] {
base: {
toConstructor: [Function: toConstructor],
setOptions: [Function (anonymous)],
collection: [Function: collection],
collation: [Function (anonymous)],
'$where': [Function (anonymous)],
where: [Function (anonymous)],
equals: [Function: equals],
eq: [Function: eq],
or: [Function: or],
nor: [Function: nor],
and: [Function: and],
gt: [Function (anonymous)],
gte: [Function (anonymous)],
lt: [Function (anonymous)],
lte: [Function (anonymous)],
ne: [Function (anonymous)],
in: [Function (anonymous)],
nin: [Function (anonymous)],
all: [Function (anonymous)],
regex: [Function (anonymous)],
size: [Function (anonymous)],
maxDistance: [Function (anonymous)],
minDistance: [Function (anonymous)],
mod: [Function (anonymous)],
exists: [Function (anonymous)],
elemMatch: [Function (anonymous)],
within: [Function: within],
box: [Function (anonymous)],
polygon: [Function (anonymous)],
circle: [Function (anonymous)],
near: [Function: near],
intersects: [Function: intersects],
geometry: [Function: geometry],
select: [Function: select],
slice: [Function (anonymous)],
sort: [Function (anonymous)],
limit: [Function (anonymous)],
skip: [Function (anonymous)],
batchSize: [Function (anonymous)],
comment: [Function (anonymous)],
maxTimeMS: [Function (anonymous)],
maxTime: [Function (anonymous)],
hint: [Function (anonymous)],
j: [Function: j],
slaveOk: [Function (anonymous)],
setReadPreference: [Function (anonymous)],
read: [Function (anonymous)],
r: [Function (anonymous)],
readConcern: [Function (anonymous)],
tailable: [Function (anonymous)],
w: [Function: writeConcern],
writeConcern: [Function: writeConcern],
wTimeout: [Function: wtimeout],
wtimeout: [Function: wtimeout],
merge: [Function (anonymous)],
find: [Function (anonymous)],
_find: [AsyncFunction: _find],
cursor: [Function (anonymous)],
findOne: [Function (anonymous)],
_findOne: [AsyncFunction: _findOne],
count: [Function (anonymous)],
_count: [AsyncFunction: _count],
distinct: [Function (anonymous)],
_distinct: [AsyncFunction: _distinct],
updateMany: [Function: updateMany],
_updateMany: [AsyncFunction (anonymous)],
updateOne: [Function: updateOne],
_updateOne: [AsyncFunction (anonymous)],
replaceOne: [Function: replaceOne],
_replaceOne: [AsyncFunction (anonymous)],
deleteOne: [Function (anonymous)],
_deleteOne: [AsyncFunction (anonymous)],
deleteMany: [Function (anonymous)],
_deleteMany: [AsyncFunction (anonymous)],
findOneAndUpdate: [Function (anonymous)],
_findOneAndUpdate: [AsyncFunction (anonymous)],
findOneAndDelete: [Function (anonymous)],
findOneAndRemove: [Function (anonymous)],
_findOneAndRemove: [AsyncFunction (anonymous)],
setTraceFunction: [Function (anonymous)],
exec: [AsyncFunction: exec],
then: [AsyncFunction (anonymous)],
selected: [Function: selected],
selectedInclusively: [Function: selectedInclusively],
selectedExclusively: [Function: selectedExclusively],
_mergeUpdate: [Function (anonymous)],
_optionsForExec: [Function (anonymous)],
_fieldsForExec: [Function (anonymous)],
_updateForExec: [Function (anonymous)],
_ensurePath: [Function (anonymous)],
_validate: [Function (anonymous)]
},
'use$geoWithin': true
},
Model: Model { undefined },
Document: [Function: Document] {
_events: undefined,
_eventsCount: 0,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
prependListener: [Function: prependListener],
once: [Function: once],
prependOnceListener: [Function: prependOnceListener],
removeListener: [Function: removeListener],
off: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
rawListeners: [Function: rawListeners],
listenerCount: [Function: listenerCount],
eventNames: [Function: eventNames],
ValidationError: [class ValidationError extends MongooseError]
},
ObjectId: [Function: ObjectId] {
schemaName: 'ObjectId',
defaultOptions: {},
get: [Function (anonymous)],
set: [Function: set],
_checkRequired: [Function (anonymous)],
_cast: [Function: castObjectId],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
isValidObjectId: [Function (anonymous)],
isObjectIdOrHexString: [Function (anonymous)],
syncIndexes: [Function (anonymous)],
Decimal128: [Function: Decimal128] {
schemaName: 'Decimal128',
defaultOptions: {},
_cast: [Function: castDecimal128],
set: [Function: set],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Mixed: [Function: Mixed] {
schemaName: 'Mixed',
defaultOptions: {},
get: [Function (anonymous)],
set: [Function: set]
},
Date: [Function: SchemaDate] {
schemaName: 'Date',
defaultOptions: {},
_cast: [Function: castDate],
set: [Function: set],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Number: [Function: SchemaNumber] {
get: [Function (anonymous)],
set: [Function: set],
_cast: [Function: castNumber],
cast: [Function: cast],
_defaultCaster: [Function (anonymous)],
schemaName: 'Number',
defaultOptions: {},
_checkRequired: [Function (anonymous)],
checkRequired: [Function (anonymous)]
},
Error: [class MongooseError extends Error] {
messages: {
DocumentNotFoundError: null,
general: [Object],
Number: [Object],
Date: [Object],
String: [Object]
},
Messages: {
DocumentNotFoundError: null,
general: [Object],
Number: [Object],
Date: [Object],
String: [Object]
},
DocumentNotFoundError: [class DocumentNotFoundError extends MongooseError],
CastError: [class CastError extends MongooseError],
ValidationError: [class ValidationError extends MongooseError],
ValidatorError: [class ValidatorError extends MongooseError],
VersionError: [class VersionError extends MongooseError],
ParallelSaveError: [class ParallelSaveError extends MongooseError],
OverwriteModelError: [class OverwriteModelError extends MongooseError],
MissingSchemaError: [class MissingSchemaError extends MongooseError],
MongooseServerSelectionError: [class MongooseServerSelectionError extends MongooseError],
DivergentArrayError: [class DivergentArrayError extends MongooseError],
StrictModeError: [class StrictModeError extends MongooseError],
StrictPopulateError: [class StrictPopulateError extends MongooseError]
},
now: [Function: now],
CastError: [class CastError extends MongooseError],
SchemaTypeOptions: [class SchemaTypeOptions],
mongo: {
BSON: [Getter],
Binary: [Getter],
BSONRegExp: [Getter],
BSONSymbol: [Getter],
BSONType: [Getter],
Code: [Getter],
DBRef: [Getter],
Decimal128: [Getter],
Double: [Getter],
Int32: [Getter],
Long: [Getter],
MaxKey: [Getter],
MinKey: [Getter],
ObjectId: [Getter],
Timestamp: [Getter],
MongoBulkWriteError: [Getter],
ChangeStreamCursor: [Getter],
MongoAPIError: [Getter],
MongoAWSError: [Getter],
MongoBatchReExecutionError: [Getter],
MongoChangeStreamError: [Getter],
MongoCompatibilityError: [Getter],
MongoCursorExhaustedError: [Getter],
MongoCursorInUseError: [Getter],
MongoDecompressionError: [Getter],
MongoDriverError: [Getter],
MongoError: [Getter],
MongoExpiredSessionError: [Getter],
MongoGridFSChunkError: [Getter],
MongoGridFSStreamError: [Getter],
MongoInvalidArgumentError: [Getter],
MongoKerberosError: [Getter],
MongoMissingCredentialsError: [Getter],
MongoMissingDependencyError: [Getter],
MongoNetworkError: [Getter],
MongoNetworkTimeoutError: [Getter],
MongoNotConnectedError: [Getter],
MongoParseError: [Getter],
MongoRuntimeError: [Getter],
MongoServerClosedError: [Getter],
MongoServerError: [Getter],
MongoServerSelectionError: [Getter],
MongoSystemError: [Getter],
MongoTailableCursorError: [Getter],
MongoTopologyClosedError: [Getter],
MongoTransactionError: [Getter],
MongoUnexpectedServerResponseError: [Getter],
MongoWriteConcernError: [Getter],
AbstractCursor: [Getter],
Admin: [Getter],
AggregationCursor: [Getter],
CancellationToken: [Getter],
ChangeStream: [Getter],
ClientSession: [Getter],
Collection: [Getter],
Db: [Getter],
FindCursor: [Getter],
GridFSBucket: [Getter],
GridFSBucketReadStream: [Getter],
GridFSBucketWriteStream: [Getter],
ListCollectionsCursor: [Getter],
ListIndexesCursor: [Getter],
MongoClient: [Getter],
OrderedBulkOperation: [Getter],
UnorderedBulkOperation: [Getter],
BatchType: [Getter],
GSSAPICanonicalizationValue: [Getter],
AuthMechanism: [Getter],
Compressor: [Getter],
CURSOR_FLAGS: [Getter],
AutoEncryptionLoggerLevel: [Getter],
MongoErrorLabel: [Getter],
ExplainVerbosity: [Getter],
ServerApiVersion: [Getter],
ReturnDocument: [Getter],
ProfilingLevel: [Getter],
ReadConcernLevel: [Getter],
ReadPreferenceMode: [Getter],
ServerType: [Getter],
TopologyType: [Getter],
ReadConcern: [Getter],
ReadPreference: [Getter],
WriteConcern: [Getter],
CommandFailedEvent: [Getter],
CommandStartedEvent: [Getter],
CommandSucceededEvent: [Getter],
ConnectionCheckedInEvent: [Getter],
ConnectionCheckedOutEvent: [Getter],
ConnectionCheckOutFailedEvent: [Getter],
ConnectionCheckOutStartedEvent: [Getter],
ConnectionClosedEvent: [Getter],
ConnectionCreatedEvent: [Getter],
ConnectionPoolClearedEvent: [Getter],
ConnectionPoolClosedEvent: [Getter],
ConnectionPoolCreatedEvent: [Getter],
ConnectionPoolMonitoringEvent: [Getter],
ConnectionPoolReadyEvent: [Getter],
ConnectionReadyEvent: [Getter],
ServerClosedEvent: [Getter],
ServerDescriptionChangedEvent: [Getter],
ServerHeartbeatFailedEvent: [Getter],
ServerHeartbeatStartedEvent: [Getter],
ServerHeartbeatSucceededEvent: [Getter],
ServerOpeningEvent: [Getter],
TopologyClosedEvent: [Getter],
TopologyDescriptionChangedEvent: [Getter],
TopologyOpeningEvent: [Getter],
SrvPollingEvent: [Getter]
},
mquery: [Function: Query] {
permissions: {
distinct: [Function],
findOneAndRemove: [Function],
findOneAndUpdate: [Function],
count: [Function]
},
_isPermitted: [Function (anonymous)],
canMerge: [Function (anonymous)],
setGlobalTraceFunction: [Function (anonymous)],
utils: {
clone: [Function: clone],
cloneObject: [Function: cloneObject],
cloneArray: [Function: cloneArray],
merge: [Function: merge],
mergeClone: [Function: mergeClone],
readPref: [Function: readPref],
readConcern: [Function: readConcern],
toString: [Function (anonymous)],
isObject: [Function (anonymous)],
keys: [Function: keys],
create: [Function: create],
inherits: [Function (anonymous)],
isArgumentsObject: [Function (anonymous)]
},
env: { isNode: [Array], isMongo: false, isBrowser: false, type: 'node' },
Collection: [class NodeCollection extends Collection],
BaseCollection: [Function: Collection] { methods: [Array] }
},
sanitizeFilter: [Function: sanitizeFilter],
trusted: [Function: trusted],
skipMiddlewareFunction: [Function: skipWrappedFunction],
overwriteMiddlewareResult: [Function: overwriteResult]
}
mongoose是什么?
Mongoose 是 MongoDB 的对象建模工具。
Mongoose 用于和MongoDB 通信(增删改查)。
Mongoose运行在Node.js 平台。
- Mongoose()是一个构造函数
- 引入mongoose模块会自动创建一个mongoose实例对象。
mongoose.connect()
- 定义:
mongoose.connect()
用于连接MongoDB数据库。
它是一个异步函数。
语法
mongoose.connect(uri)
mongoose.connect(数据库连接字符串)
返回值
返回一个Promise对象
示例
promise.then()
定义
then()
方法为promise绑定回调函数。
语法
promise.then(resolved,rejected)
promise.then((data) => {
//在异步操作成功时,处理异步操作的结果
},(error) => {
//在异步操作失败时,输出错误的原因
})
//一个参数:大多时候我们更加关注异步操作成功
promise.then((resolved) => {
//在异步操作成功时,处理异步操作的结果
})
//then()方法可以链式调用
promise.then((resolved) => {
//在异步操作成功时,处理异步操作的结果
})
.then((resolved) => {})
.then((resolved) => {})
.catch(error => {//捕获错误信息})
then() 方法最多接受两个参数:
resolved :Promise 已完成的回调函数。
rejected: Promise已拒绝的回调函数。
返回值
- 返回一个等效的prmose对象。
示例
promise.catch()
- 定义:
catch()
方法用于为promise对象绑定请求失败时的回调函数。
catch()
方法用于捕获错误信息。
语法
promise.catch((err) => {})
返回值
返回一个promise对象。
示例
mongoose.model()
- 定义:
用于创建与MongoDB数据库通信的工具。
该工具在这里意思就是:指一个构造函数。
构造函数可以实例化一个对象。
通过实例对象的方法与数据库进行通信。
语法
const Blog = mongoose.model('模型名称',模型原型)
const Blog = mongoose.model('模型名称',blogSchema)
返回值
返回大写的构造函数(Model())
示例
Schema()
- 定义:
Schema()
是一个构造函数/类。
Schema()
用于描述数据表的结构。
- 数据库:由多个数据库表构成
- 数据库表:由多个document(记录)构成。
- Document: 由字段和值构成。
语法
new Schema({定义表结构},{选项对象})
const blogSchema = new Schema({
//定义title字段
title: {
//字段类型:字符串
type: String,
//字段是否必写: true
required: true
},
body: {
type: String,
required: true
}
}, {})
- 定义表结构: 定义有哪些字段、每个字段的数据类型、是否必填等
- 选项对象:提供了一些参数,用来配置第一个参数
返回值
返回schema实例对象,表示数据结构。
示例:
Bootstrap:.Containers
<div class='Containers'></div>
-定义:
- 表示一个容器。
- Containers类是Bootstrap是一个构建基本结构的类;
- 用法1:宽度固定
<div class='Containers'></div>
- 用法2:宽度不固定100%;流式布局
<div class="container-fluid"></div>
------
Background:背景色+文字颜色
bg-body-tertiary
-------
#.link:设置链接颜色
- 定义:link-primary