Node.js:ExpressWeb
数据库操作 ODM mongoose
### 安装 ```js npm install mongoose ``` ### 导入 ```js // Using Node.js `require()` const mongoose = require('mongoose'); // Using ES6 imports import mongoose from 'mongoose'; //Or, using Deno's createRequire() for CommonJS support as follows. import { createRequire } from 'https://deno.land/std@0.177.0/node/module.ts'; const require = createRequire(import.meta.url); const mongoose = require('mongoose'); ``` ### 连接到 MongoDB ```js // 导入 mongoose 模块 const mongoose = require("mongoose"); // 设置默认 mongoose 连接 const mongoDB = "mongodb://127.0.0.1/my_database"; mongoose.connect(mongoDB); // 让 mongoose 使用全局 Promise 库 mongoose.Promise = global.Promise; // 取得默认连接 const db = mongoose.connection; // 将连接与错误事件绑定(以获得连接错误的提示) db.on("error", console.error.bind(console, "MongoDB 连接错误:")); //导出 module.exports = mongoose; ``` ### 创建模型 ```js // 定义一个模式 const Schema = mongoose.Schema; const SomeModelSchema = new Schema({ a_string: String, a_date: Date, }); // 使用模式“编译”模型 const SomeModel = mongoose.model("SomeModel", SomeModelSchema); ``` ### 模式类型(字段) ```typescript const schema = new Schema({ name: String, binary: Buffer, living: Boolean, updated: { type: Date, default: Date.now }, age: { type: Number, min: 18, max: 65, required: true }, mixed: Schema.Types.Mixed, _someId: Schema.Types.ObjectId, array: [], ofString: [String], // 其他类型也可使用数组 nested: { stuff: { type: String, lowercase: true, trim: true } }, title: { type: String, default: 'hahaha' }, age: { type: Number, min: 18, index: true }, bio: { type: String, match: /[a-z]/ }, date: { type: Date, default: Date.now }, buff: Buffer, author: {type: Schema.Types.ObjectId, ref: "Author", require: true}, //一个关联 genre: [{type: Schema.Types.ObjectId, ref: "Genre"}],//多个关联 asset: { name: String, type: { type: String } // works. asset is an object with a type property } }); ```
顶部
收展
底部
[TOC]
目录
Express/Node 入门
路由
中间件
API接口 express()
API接口 app()
API接口 res()
API接口 Router()
数据库操作 ODM mongoose
相关推荐
Node.js教程:新手入门
Node.js接口
朴灵《深入浅出 Node.js》