數(shù)據(jù)庫

使用Node.js開發(fā)App的步驟

  1. 創(chuàng)建項目目錄

    mkdir myapp
    cd myapp
    # 合并以上兩步驟
    mkdir myapp && cd myapp
    
  2. 初始化

    npm init --yes //目的:創(chuàng)建package.json文件磅崭,該文件記錄了項目項目信息及項目中所有使用的模塊。
    
  3. 創(chuàng)建項目結(jié)構(gòu)

    myapp
    - views 
    - public
    - routes
    - package.json
    - package-lock.json
    - app.js
    
  4. 安裝模塊

    npm install express
    
  5. 引入模塊

    const express = require('express')
    
  6. 寫需求

    .....
    

網(wǎng)站根目錄

  1. 根目錄 VS 用戶根目錄

         \           vs        ~
    
  2. 查看當(dāng)前位置: pwd

  3. 項目根目錄:訪問權(quán)限設(shè)置為公開的应闯、任何人都可以訪問的蛀序。


public目錄

定義

Public 目錄是Node.js中存放網(wǎng)站靜態(tài)文件的目錄欢瞪。靜態(tài)文件包括:

  • 圖片
  • css文件
  • js文件
  • 字體文件
mkdir public && cd public
mkdir css js images

Public : 公共的、共同的徐裸、公開


express框架

  • 框架的核心是構(gòu)造函數(shù)express()
  • Express()** 構(gòu)造函數(shù)用于創(chuàng)建一個APP實例(服務(wù)器類型的app)**
  • express是基于Node.js平臺
  • Node.js平臺是運行js文件的遣鼓。

  • Node.js項目目錄
    • index.js app.js server.js
    • views
      • html視圖模版
        • ejs視圖引擎
    • public
      • 引入靜態(tài)資源
  • 普通項目目錄
    • index.html
    • css
      • style.css
    • js
      • Script.js

知識點1:express.static()

定義

語法

返回值

示例


知識點2:創(chuàng)建數(shù)據(jù)庫

方案1:創(chuàng)建本地mongodb數(shù)據(jù)庫

  1. 啟動mongodb數(shù)據(jù)庫

    # window系統(tǒng)
    服務(wù) => 右鍵 => 啟動
    # Mac OS
    brew services start mongodb/brew/mongodb-community 
    
  2. 連接數(shù)據(jù)庫(怎么和數(shù)據(jù)庫通信?)

    1. 可以使用可視化軟件Compass
    2. 非可視化軟件:mongosh
mongosh "mongodb://localhost:27017"
  1. 創(chuàng)建數(shù)據(jù)庫: zhangsanblog

    1. 使用compass手動創(chuàng)建

    2. 使用mongosh手動創(chuàng)建

      use zhangsanblog
      
  2. 創(chuàng)建數(shù)據(jù)庫用戶

    1. 語法

      Db.createUser({
        user: 'zhangsan',
        pwd: '123456',
        roles: [{ role:"readWrite",db:"config"},"clusterAdmin"],
        roles: ["readWrite"]
      })
      

方案2:創(chuàng)建云數(shù)據(jù)庫

  1. 登錄Atlas賬戶
  2. 創(chuàng)建數(shù)據(jù)庫 : zhangsanblog
  3. 創(chuàng)建用戶: zhangsan Zxcvbn123456

知識點3:連接字符串

定義

連接字符串特指在App開發(fā)過程中連接數(shù)據(jù)庫的地址重贺。

語法

"協(xié)議://用戶名:密碼@數(shù)據(jù)庫地址/數(shù)據(jù)庫名"

云數(shù)據(jù)庫的連接字符串

從云數(shù)據(jù)庫復(fù)制的連接字符串:
'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'

本地數(shù)據(jù)庫的連接字符串

"mongodb://zhangsan:123456@127.0.0.1:27107/zhangsanblog"
"mongodb://zhangsan:123456@localhost:27107/zhangsanblog"

知識點4:Node和MongoDB的通信

通信方式有兩種:

  • Mongodb模塊:
    • mongodb模塊是Node.js原生提供的與mongoDB數(shù)據(jù)庫通信的API骑祟。
  • Mongoose模塊:
    • 是第三方提供的在Node平臺與MongoDB數(shù)據(jù)庫通信的方式。
    • Mongoose是一個庫气笙。
    • 庫:就是函數(shù)的集合次企。
    • Mongoose庫包裹Node API。

知識點5:使用Mongoose模塊連接數(shù)據(jù)庫

const mongoose = require('mongoose')

mongoose.connect(uri)
    .then((result) => {
        console.log('數(shù)據(jù)庫已經(jīng)連接')
    })
    .catch( err => console.log(err))

mongoose是什么潜圃?

  • 核心:mongoose()構(gòu)造函數(shù)
  • mongoose是一個ODM(對象數(shù)據(jù)模型)缸棵。(object Data Model)
  • 使用js對象的語法來映射mongoose數(shù)據(jù)庫種的表和document
  • collection:數(shù)據(jù)庫中的表;
  • document:數(shù)據(jù)中的文檔秉犹;

打印mongoose

const mongoose = require('mongoose') 引入mongoose模塊會自動創(chuàng)建mongoose實例對象蛉谜。

  • mongoose是一個對象
  • Mongoose.connections 屬性
  • mongoose.Schema :構(gòu)造函數(shù)
  • Mongoose.model: 函數(shù)
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()是一個構(gòu)造函數(shù)
  • 引入mongoose模塊會自動創(chuàng)建一個mongoose實例對象鸳劳。

mongoose.connect()

  • 定義:

mongoose.connect()用于連接MongoDB數(shù)據(jù)庫狰贯。

它是一個異步函數(shù)。

語法

mongoose.connect(uri)
mongoose.connect(數(shù)據(jù)庫連接字符串)

返回值

返回一個Promise對象

示例


promise.then()

定義

then()方法為promise綁定回調(diào)函數(shù)赏廓。

語法

promise.then(resolved,rejected)
promise.then((data) => {
  //在異步操作成功時涵紊,處理異步操作的結(jié)果
},(error) => {
  //在異步操作失敗時,輸出錯誤的原因
})

//一個參數(shù):大多時候我們更加關(guān)注異步操作成功
promise.then((resolved) => {
  //在異步操作成功時幔摸,處理異步操作的結(jié)果
})

//then()方法可以鏈?zhǔn)秸{(diào)用
promise.then((resolved) => {
  //在異步操作成功時摸柄,處理異步操作的結(jié)果
})
  .then((resolved) => {})
    .then((resolved) => {})
    .catch(error => {//捕獲錯誤信息})

then() 方法最多接受兩個參數(shù):

  • resolved :Promise 已完成的回調(diào)函數(shù)。

  • rejected: Promise已拒絕的回調(diào)函數(shù)既忆。

返回值

  • 返回一個等效的prmose對象驱负。

示例

promise.catch()

  • 定義:

catch()方法用于為promise對象綁定請求失敗時的回調(diào)函數(shù)嗦玖。

catch()方法用于捕獲錯誤信息。

語法

promise.catch((err) => {})

返回值

返回一個promise對象跃脊。

示例

mongoose.model()

  • 定義:

用于創(chuàng)建與MongoDB數(shù)據(jù)庫通信的工具宇挫。

該工具在這里意思就是:指一個構(gòu)造函數(shù)。

構(gòu)造函數(shù)可以實例化一個對象酪术。

通過實例對象的方法與數(shù)據(jù)庫進行通信器瘪。

語法

const Blog = mongoose.model('模型名稱',模型原型)
const Blog = mongoose.model('模型名稱',blogSchema)

返回值

返回大寫的構(gòu)造函數(shù)(Model())

示例

Schema()

  • 定義:

Schema()是一個構(gòu)造函數(shù)/類。

Schema()用于描述數(shù)據(jù)表的結(jié)構(gòu)绘雁。

  • 數(shù)據(jù)庫:由多個數(shù)據(jù)庫表構(gòu)成
  • 數(shù)據(jù)庫表:由多個document(記錄)構(gòu)成橡疼。
  • Document: 由字段和值構(gòu)成。

語法

 new Schema({定義表結(jié)構(gòu)},{選項對象})

const blogSchema = new Schema({
  //定義title字段
  title: {
    //字段類型:字符串
    type: String,
    //字段是否必寫: true
    required: true
  },
  body: {
    type: String,
    required: true
  }
}, {})
  • 定義表結(jié)構(gòu): 定義有哪些字段庐舟、每個字段的數(shù)據(jù)類型衰齐、是否必填等
  • 選項對象:提供了一些參數(shù),用來配置第一個參數(shù)

返回值

返回schema實例對象,表示數(shù)據(jù)結(jié)構(gòu)继阻。

示例:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末耻涛,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子瘟檩,更是在濱河造成了極大的恐慌抹缕,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件墨辛,死亡現(xiàn)場離奇詭異卓研,居然都是意外死亡,警方通過查閱死者的電腦和手機睹簇,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門奏赘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人太惠,你說我怎么就攤上這事磨淌。” “怎么了凿渊?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵梁只,是天一觀的道長。 經(jīng)常有香客問我埃脏,道長搪锣,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任彩掐,我火速辦了婚禮构舟,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘堵幽。我一直安慰自己狗超,他們只是感情好监嗜,可當(dāng)我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著抡谐,像睡著了一般。 火紅的嫁衣襯著肌膚如雪桐猬。 梳的紋絲不亂的頭發(fā)上麦撵,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機與錄音溃肪,去河邊找鬼免胃。 笑死,一個胖子當(dāng)著我的面吹牛惫撰,可吹牛的內(nèi)容都是我干的羔沙。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼厨钻,長吁一口氣:“原來是場噩夢啊……” “哼扼雏!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起夯膀,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤诗充,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后诱建,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蝴蜓,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年俺猿,在試婚紗的時候發(fā)現(xiàn)自己被綠了茎匠。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡押袍,死狀恐怖诵冒,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情谊惭,我是刑警寧澤造烁,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站午笛,受9級特大地震影響惭蟋,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜药磺,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一告组、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧癌佩,春花似錦木缝、人聲如沸便锨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽放案。三九已至,卻和暖如春矫俺,著一層夾襖步出監(jiān)牢的瞬間吱殉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工厘托, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留友雳,地道東北人。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓铅匹,卻偏偏與公主長得像押赊,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子包斑,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容