Getting Started入门

First be sure you have MongoDB and Node.js installed.首先要确保你已经安装了 MongoDBNode.js

Next install Mongoose from the command line using npm:接下来使用npm从命令行安装Mongoose:

$ npm install mongoose --save

Now say we like fuzzy kittens and want to record every kitten we ever meet in MongoDB. 现在说我们喜欢毛茸茸的小猫,想把我们在MongoDB中遇到的每一只小猫都记录下来。The first thing we need to do is include mongoose in our project and open a connection to the test database on our locally running instance of MongoDB.我们需要做的第一件事是在项目中包括mongoose,并在本地运行的MongoDB实例上打开与test数据库的连接。

// getting-started.js
const mongoose = require('mongoose');

main().catch(err => console.log(err));

async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/test');

// use `await mongoose.connect('mongodb://user:password@127.0.0.1:27017/test');` if your database has auth enabled如果你的数据库已启用身份验证,请使用`await mongoose.connect('mongodb://user:password@127.0.0.1:27017/test');`
}

For brevity, let's assume that all following code is within the main() function.为了简洁起见,让我们假设以下所有代码都在main()函数中。

With Mongoose, everything is derived from a Schema. Let's get a reference to it and define our kittens.有了Mongoose,一切都是从 Schema派生出来的。让我们参考一下,定义一下小猫。

const kittySchema = new mongoose.Schema({
name: String
});

So far so good. 到现在为止,一直都还不错。We've got a schema with one property, name, which will be a String. 我们有一个模式,它有一个属性name,它将是一个StringThe next step is compiling our schema into a Model.下一步是将模式编译成一个 模型

const Kitten = mongoose.model('Kitten', kittySchema);

A model is a class with which we construct documents. 模型是用来构造文档的类。In this case, each document will be a kitten with properties and behaviors as declared in our schema. 在这种情况下,每个文档都将是一个小猫,具有模式中声明的属性和行为。Let's create a kitten document representing the little guy we just met on the sidewalk outside:让我们创建一个小猫文档,代表我们刚刚在外面人行道上遇到的小家伙:

const silence = new Kitten({ name: 'Silence' });
console.log(silence.name); // 'Silence'

Kittens can meow, so let's take a look at how to add "speak" functionality to our documents:小猫会叫,所以让我们看看如何在文档中添加“说话”功能:

// NOTE: methods must be added to the schema before compiling it with mongoose.model()必须先将方法添加到架构中,然后再使用`mongoose.model()`进行编译
kittySchema.methods.speak = function speak() {
const greeting = this.name
? 'Meow name is ' + this.name
: 'I don\'t have a name';
console.log(greeting);
};

const Kitten = mongoose.model('Kitten', kittySchema);

Functions added to the methods property of a schema get compiled into the Model prototype and exposed on each document instance:添加到模式的methods属性中的函数被编译到模型原型中,并在每个文档实例上公开:

const fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"

We have talking kittens! But we still haven't saved anything to MongoDB. 我们有会说话的小猫!但我们仍然没有将任何内容保存到MongoDB中。Each document can be saved to the database by calling its save method. The first argument to the callback will be an error if any occurred.每个文档都可以通过调用其 save方法保存到数据库中。如果出现任何错误,回调的第一个参数将是错误。

await fluffy.save();
fluffy.speak();

Say time goes by and we want to display all the kittens we've seen. We can access all of the kitten documents through our Kitten model.假设时间过去了,我们想展示我们看到的所有小猫。我们可以通过小猫 model访问所有的小猫文档。

const kittens = await Kitten.find();
console.log(kittens);

We just logged all of the kittens in our db to the console. 我们刚刚将数据库中的所有小猫都记录到控制台中。If we want to filter our kittens by name, Mongoose supports MongoDBs rich querying syntax.如果我们想按名称筛选小猫,Mongoose支持MongoDB丰富的 查询语法。

await Kitten.find({ name: /^fluff/ });

This performs a search for all documents with a name property that begins with "fluff" and returns the result as an array of kittens to the callback.这将使用以“fluff”开头的name属性搜索所有文档,并将结果作为一个小猫数组返回给回调。

Congratulations祝贺

That's the end of our quick start. We created a schema, added a custom document method, saved and queried kittens in MongoDB using Mongoose. 快速起步到此结束。我们创建了一个模式,添加了一个自定义的文档方法,使用Mongoose在MongoDB中保存和查询了小猫。Head over to the guide, or API docs for more.请参阅 指南API文档了解更多信息。