# Mongoose
Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. Mongoose supports [Node.js](https://nodejs.org/en/) and [Deno](https://deno.land/) (alpha).
[![Build Status](https://github.com/Automattic/mongoose/workflows/Test/badge.svg)](https://github.com/Automattic/mongoose)
[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose)
[![Deno version](https://deno.land/badge/mongoose/version)](https://deno.land/x/mongoose)
[![Deno popularity](https://deno.land/badge/mongoose/popularity)](https://deno.land/x/mongoose)
[![npm](https://nodei.co/npm/mongoose.png)](https://www.npmjs.com/package/mongoose)
## Documentation
The official documentation website is [mongoosejs.com](http://mongoosejs.com/).
Mongoose 7.0.0 was released on February 27, 2023. You can find more details on [backwards breaking changes in 7.0.0 on our docs site](https://mongoosejs.com/docs/migrating_to_7.html).
## Support
* [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
* [Bug Reports](https://github.com/Automattic/mongoose/issues/)
* [Mongoose Slack Channel](http://slack.mongoosejs.io/)
* [Help Forum](http://groups.google.com/group/mongoose-orm)
* [MongoDB Support](https://www.mongodb.com/docs/manual/support/)
## Plugins
Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community. Next, learn how to write your own plugin from the [docs](http://mongoosejs.com/docs/plugins.html) or [this blog post](http://thecodebarbarian.com/2015/03/06/guide-to-mongoose-plugins).
## Contributors
Pull requests are always welcome! Please base pull requests against the `master`
branch and follow the [contributing guide](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md).
If your pull requests makes documentation changes, please do **not**
modify any `.html` files. The `.html` files are compiled code, so please make
your changes in `docs/*.pug`, `lib/*.js`, or `test/docs/*.js`.
View all 400+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors).
## Installation
First install [Node.js](http://nodejs.org/) and [MongoDB](https://www.mongodb.org/downloads). Then:
```sh
npm install mongoose
```
Mongoose 6.8.0 also includes alpha support for [Deno](https://deno.land/).
## Importing
```javascript
// Using Node.js `require()`
const mongoose = require('mongoose');
// Using ES6 imports
import mongoose from 'mongoose';
```
Or, using [Deno's `createRequire()` for CommonJS support](https://deno.land/[email protected]/node/README.md?source=#commonjs-modules-loading) as follows.
```javascript
import { createRequire } from 'https://deno.land/[email protected]/node/module.ts';
const require = createRequire(import.meta.url);
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/test')
.then(() => console.log('Connected!'));
```
You can then run the above script using the following.
```sh
deno run --allow-net --allow-read --allow-sys --allow-env mongoose-test.js
```
## Mongoose for Enterprise
Available as part of the Tidelift Subscription
The maintainers of mongoose and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-mongoose?utm_source=npm-mongoose&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Overview
### Connecting to MongoDB
First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`.
Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
```js
await mongoose.connect('mongodb://127.0.0.1/my_database');
```
Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`.
**Note:** *If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.*
**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.
### Defining a Model
Models are defined through the `Schema` interface.
```js
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const BlogPost = new Schema({
author: ObjectId,
title: String,
body: String,
date: Date
});
```
Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
* [Defaults](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-default)
* [Getters](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-get)
* [Setters](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set)
* [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
* [Middleware](http://mongoosejs.com/docs/middleware.html)
* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
* [Plugins](http://mongoosejs.com/docs/plugins.html)
* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)
The following example shows some of these features:
```js
const Comment = new Schema({
name: { 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
});
// a setter
Comment.path('name').set(function(v) {
return capitalize(v);
});
// middleware
Comment.pre('save', function(next) {
notify(this.get('email'));
next();
});
```
Take a look at the example in [`examples/schema/schema.js`](https://github.com/Automattic/mongoose/blob/master/examples/schema/schema.js) for an end-to-end example of a typical setup.
### Accessing a Model
Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
```js
const MyModel = mongoose.model('ModelName');
```
Or just do it all at once
```js
const MyModel = mongoose.model('ModelName', mySchema);
```
The first argument is the *singular* name of the collection your model is for. **Mongoose automatically looks for the *plural* version of your model name.** For example, if you use
```js
const MyModel = mongoose.model('Ticket', mySchema);
```
Then `MyModel` will use the **tickets** collection, not the **ticket** collection. For more details read the [model docs](https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-model).
Once we have our model, we can then instantiate it, and save it:
```js
const instance = new MyModel();
instance.my.key = 'hello';
await instance.save();
```
Or we can find documents from the same collection
```js
await MyModel.find({});
```
You can also `findOne`, `findById`, `update`, etc.
```js
const instance = await MyModel.findOne({ /* ... */ });
console.log(instance.my.key); // 'hello'
```
For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:
```js
const conn = mongoose.createConnection('your connection string');
const MyModel = conn.model
没有合适的资源?快使用搜索试试~ 我知道了~
mongoose-master.zip
共705个文件
js:472个
md:71个
ts:61个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
5星 · 超过95%的资源 1 下载量 24 浏览量
2023-10-22
09:32:49
上传
评论
收藏 1.79MB ZIP 举报
温馨提示
mongoose-master.zip
资源推荐
资源详情
资源评论
收起资源包目录
mongoose-master.zip (705个子文件)
.markdownlint-cli2.cjs 2KB
CNAME 15B
mongoose5.css 5KB
style.css 5KB
api.css 3KB
github.css 2KB
inlinecpc.css 959B
carbonads.css 544B
.gitignore 940B
.gitignore 13B
index.html 122B
favicon.ico 1KB
localize-mongoose-ad-banner-2x.jpg 205KB
fortunegames.jpg 21KB
document.test.js 350KB
model.populate.test.js 325KB
model.test.js 210KB
model.js 174KB
query.js 167KB
document.js 138KB
query.test.js 124KB
schema.test.js 95KB
model.updateOne.test.js 92KB
schema.js 85KB
model.discriminator.test.js 70KB
model.findOneAndUpdate.test.js 67KB
types.array.test.js 56KB
model.querying.test.js 56KB
connection.test.js 50KB
schematype.js 50KB
index.js 48KB
connection.js 47KB
schema.validation.test.js 47KB
model.discriminator.querying.test.js 40KB
index.test.js 36KB
aggregate.test.js 36KB
aggregate.js 34KB
timestamps.test.js 31KB
types.map.test.js 29KB
index.js 28KB
query.cursor.test.js 26KB
getModelsMapForPopulate.js 25KB
schema.select.test.js 24KB
document.populate.test.js 24KB
model.query.casting.test.js 24KB
validation.test.js 22KB
utils.js 22KB
model.indexes.test.js 21KB
model.insertMany.test.js 21KB
types.documentarray.test.js 20KB
array.js 19KB
string.js 19KB
versioning.test.js 18KB
documentarray.js 18KB
api.js 17KB
website.js 16KB
castUpdate.js 16KB
document.modified.test.js 15KB
QueryCursor.js 15KB
discriminators.test.js 15KB
model.field.selection.test.js 15KB
model.middleware.preposttypes.test.js 15KB
query.middleware.test.js 14KB
cast.js 14KB
types.buffer.test.js 14KB
model.findOneAndReplace.test.js 14KB
collection.js 14KB
transactions.test.js 13KB
multiop.js 13KB
document.strict.test.js 12KB
connection.js 12KB
queryhelpers.js 11KB
SubdocumentPath.js 11KB
date.js 11KB
number.js 11KB
assignVals.js 11KB
model.middleware.test.js 11KB
indexes.getRelatedIndexes.test.js 11KB
document.isselected.test.js 10KB
model.populate.setting.test.js 10KB
index.js 10KB
model.findOneAndDelete.test.js 10KB
AggregationCursor.js 10KB
utils.test.js 10KB
population.js 10KB
subdocument.js 10KB
castBulkWrite.js 9KB
model.findOneAndRemove.test.js 9KB
clone.test.js 9KB
map.js 9KB
schematype.test.js 8KB
shard.test.js 8KB
uuid.js 8KB
lean.test.js 8KB
virtuals.test.js 8KB
update.castArrayFilters.test.js 8KB
model.create.test.js 8KB
errors.validation.test.js 8KB
getSchemaTypes.js 8KB
read.js 8KB
共 705 条
- 1
- 2
- 3
- 4
- 5
- 6
- 8
资源评论
- 疯狂的石头已被占用2024-01-24果断支持这个资源,资源解决了当前遇到的问题,给了新的灵感,感谢分享~
YunFeiDong
- 粉丝: 152
- 资源: 3908
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- MATLAB大数据仿真案例-蚁群算法(ACO)用于求解旅行商(TSP)问题.rar
- MySQL基础知识-个人笔记.rar
- Project8.ipynb
- Python实现BWO-LSTM白鲸算法优化长短期记忆神经网络时间序列预测(完整源码和数据)
- C语言实现文件读写操作的几种常用方法-C 语言.rar
- RK 3568 Android11 版本的梯形校正补丁
- 基于pyqt yolov5 dlib的驾驶员行为监控系统源码+模型.zip
- python代码案例详解-旅行商问题的多种求解算法.rar
- 单相电力电子负载仿真,PWM整流+单相并网逆变
- C语言功能模块(配置文件读取 、debug日志记录等).zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功