入门
¥Getting Started
¥First be sure you have MongoDB and Node.js installed.
接下来使用 npm
从命令行安装 Mongoose:
¥Next install Mongoose from the command line using npm
:
npm install mongoose --save
现在假设我们喜欢毛茸茸的小猫,并且想在 MongoDB 中记录我们遇到的每只小猫。我们需要做的第一件事是在我们的项目中包含 mongoose,并在本地运行的 MongoDB 实例上打开与 test
数据库的连接。
¥Now say we like fuzzy kittens and want to record every kitten we ever meet
in 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.
// 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
}
为了简洁起见,我们假设以下所有代码都在 main()
函数内。
¥For brevity, let's assume that all following code is within the main()
function.
对于 Mongoose,一切都源自 结构。让我们参考它并定义我们的小猫。
¥With Mongoose, everything is derived from a Schema. Let's get a reference to it and define our kittens.
const kittySchema = new mongoose.Schema({
name: String
});
到目前为止,一切都很好。我们有一个具有一个属性 name
的模式,该属性将是 String
。下一步是将我们的结构编译成 模型。
¥So far so good. We've got a schema with one property, name
, which will be a String
. The 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()
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);
添加到结构的 methods
属性的函数被编译到 Model
原型中并在每个文档实例上公开:
¥Functions added to the methods
property of a schema get compiled into
the Model
prototype and exposed on each document instance:
const fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"
我们有会说话的小猫!但我们仍然没有向 MongoDB 保存任何内容。每个文档都可以通过调用其 保存 方法保存到数据库中。如果发生任何错误,回调的第一个参数将是一个错误。
¥We have talking kittens! But we still haven't saved anything to 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.
await fluffy.save();
fluffy.speak();
假设时间过去了,我们想展示我们见过的所有小猫。我们可以通过 Kitten 模型 访问所有小猫文档。
¥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.
const kittens = await Kitten.find();
console.log(kittens);
我们刚刚将数据库中的所有小猫记录到控制台。如果我们想按名字过滤小猫,Mongoose 支持 MongoDB 丰富的 查询 语法。
¥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.
await Kitten.find({ name: /^fluff/ });
这将搜索名称属性以 "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.
恭喜
¥Congratulations
我们的快速入门到此结束。我们创建了一个结构,添加了一个自定义文档方法,使用 Mongoose 在 MongoDB 中保存和查询小猫。请前往 指南 或 API 文档 了解更多信息。
¥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. Head over to the guide, or API docs for more.