博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Mongoose轻松开发Node.js和MongoDB应用
阅读量:2510 次
发布时间:2019-05-11

本文共 10264 字,大约阅读时间需要 34 分钟。

Node.js and MongoDB are a pair made for each other. Being able to use JSON across the board and JavaScript makes development very easy. This is why you get popular stacks like the MEAN stack that uses Node, Express (a Node.js framework), MongoDB, and AngularJS.

Node.js和MongoDB是彼此配对的。 能够全面使用JSON和JavaScript使得开发非常容易。 这就是为什么您会得到流行的堆栈,例如使用Node,Express(Node.js框架),MongoDB和AngularJS的MEAN堆栈。

CRUD is something that is necessary in most every application out there. We have to create, read, update, and delete information all the time.

CRUD是大多数大多数应用程序所必需的。 我们必须始终创建,读取,更新和删除信息。

Today we'll be looking at code samples to handle CRUD operations in a Node.js, ExpressJS, and MongoDB application. We'll use the popular Node package, .

今天,我们将研究在Node.js,ExpressJS和MongoDB应用程序中处理CRUD操作的代码示例。 我们将使用流行的Node包 。

These code samples were used to create a since you are performing CRUD functions when creating an API. Read through that tutorial to see these commands in action. This article will be more of a reference for the various commands and their usage.

这些代码示例用于创建因为在创建API时您正在执行CRUD函数。 通读该教程以了解这些命令的实际作用。 本文将为各种命令及其用法提供更多参考。

什么是猫鼬? (What Is Mongoose?)

is an object modeling package for Node that essentially works like an ORM that you would see in other languages (like ).

是Node的对象建模软件包,其本质上就像您在其他语言中看到的ORM一样工作(例如 )。

Mongoose allows us to have access to the MongoDB commands for CRUD simply and easily. To use mongoose, make sure that you add it to you Node project by using the following command:

Mongoose使我们能够简单,轻松地访问用于CRUD的MongoDB命令。 要使用猫鼬,请确保使用以下命令将其添加到Node项目中:

$ npm install mongoose --save

Now that we have the package, we just have to grab it in our project:

现在我们有了软件包,我们只需要在我们的项目中抓取它:

var mongoose = require('mongoose');

We also have to connect to a MongoDB database (either local or hosted):

我们还必须连接到MongoDB数据库(本地或托管):

mongoose.connect('mongodb://localhost/myappdatabase');

Let's get to the commands.

让我们来看看命令。

定义模型 (Defining a Model)

Before we can handle CRUD operations, we will need a . These models are constructors that we define. They represent documents which can be saved and retrieved from our database.

在处理CRUD操作之前,我们需要一个 。 这些模型是我们定义的构造函数。 它们代表可以从我们的数据库中保存和检索的文档

Mongoose Schema The is what is used to define attributes for our documents.

猫鼬模式 用于定义文档的属性。

Mongoose Methods Methods can also be defined on a mongoose schema. These are methods

猫鼬方法方法也可以在猫鼬模式中定义。 这些是方法

用户样本模型 (Sample Model for Users)

// grab the things we needvar mongoose = require('mongoose');var Schema = mongoose.Schema;// create a schemavar userSchema = new Schema({  name: String,  username: { type: String, required: true, unique: true },  password: { type: String, required: true },  admin: Boolean,  location: String,  meta: {    age: Number,    website: String  },  created_at: Date,  updated_at: Date});// the schema is useless so far// we need to create a model using itvar User = mongoose.model('User', userSchema);// make this available to our users in our Node applicationsmodule.exports = User;

This is how a Schema is defined. We must grab mongoose and mongoose.Schema. Then we can define our attributes on our userSchema for all the things we need for our user profiles. Also notice how we can define nested objects as in the meta attribute.

这就是定义架构的方式。 我们必须抓住mongoosemongoose.Schema 。 然后,我们可以在userSchema上定义我们的用户配置文件所需的所有属性。 还要注意我们如何像meta属性一样定义嵌套对象。

The allowed SchemaTypes are:

允许的SchemaTypes是:

  • String

  • Number

  • Date

    日期
  • Buffer

    缓冲
  • Boolean

    布尔型
  • Mixed

    混合的
  • ObjectId

    对象编号
  • Array

    数组

We will then create the mongoose Model by calling mongoose.model. We can also do more with this like creating specific methods. This is a good place to create a method to hash a password.

然后,我们将通过调用mongoose.model创建猫鼬模型。 我们还可以做更多的事情,例如创建特定的方法。 这是创建哈希密码方法的好地方。

自定义方法 (Custom Method)

// grab the things we needvar mongoose = require('mongoose');var Schema = mongoose.Schema;// create a schemavar userSchema ...// custom method to add string to end of name// you can create more important methods like name validations or formatting// you can also do queries and find similar users userSchema.methods.dudify = function() {  // add some stuff to the users name  this.name = this.name + '-dude';   return this.name;};// the schema is useless so far// we need to create a model using itvar User = mongoose.model('User', userSchema);// make this available to our users in our Node applicationsmodule.exports = User;

样品用量 (Sample Usage)

Now we have a custom model and method that we can call in our code:

现在,我们有了可以在代码中调用的自定义模型和方法:

// if our user.js file is at app/models/user.jsvar User = require('./app/models/user');// create a new user called chrisvar chris = new User({  name: 'Chris',  username: 'sevilayha',  password: 'password' });// call the custom method. this will just add -dude to his name// user will now be Chris-dudechris.dudify(function(err, name) {  if (err) throw err;  console.log('Your new name is ' + name);});// call the built-in save method to save to the databasechris.save(function(err) {  if (err) throw err;  console.log('User saved successfully!');});

This is a very useless custom method, but the idea for how to create a custom method and use it stands. We can use this for making sure that passwords are hashed before saving, having a method to compare passwords, find users with similar attributes, and more.

这是一个非常无用的自定义方法,但是关于如何创建和使用自定义方法的想法仍然存在。 我们可以使用它来确保在保存之前对密码进行哈希处理,可以使用一种方法来比较密码,查找具有相似属性的用户等等。

保存前运行功能 (Run a Function Before Saving)

We also want to have a created_at variable to know when the record was created. We can use the Schema pre method to have operations happen before an object is saved.

我们还希望有一个created_at变量来知道何时创建记录。 我们可以使用Schema pre方法在保存对象之前进行操作。

Here is the code to add to our Schema to have the date added to created_at if this is the first save, and to updated_at on every save:

以下是添加到我们的架构中的代码,如果是第一次保存,则将日期添加到created_at ,每次保存时将日期添加到updated_at

// on every save, add the dateuserSchema.pre('save', function(next) {  // get the current date  var currentDate = new Date();  // change the updated_at field to current date  this.updated_at = currentDate;  // if created_at doesn't exist, add to that field  if (!this.created_at)    this.created_at = currentDate;  next();});

Now on every save, we will add our dates. This is also a great place to hash passwords to be sure that we never save plaintext passwords.

现在,在每次保存时,我们将添加日期。 这也是散列密码的好地方,以确保我们永远不会保存明文密码。

We can also define more things on our models and schemas like statics and indexes. Be sure to take a look at the for more information.

我们还可以在模型和架构上定义更多内容,例如静态变量和索引。 请务必查看以获取更多信息。

创造 (Create)

We'll be using the User method we created earlier. The built-in save method on mongoose Models is what is used to create a user:

我们将使用之前创建的User方法。 猫鼬模型的内置save方法是用于创建用户的方法:

// grab the user modelvar User = require('./app/models/user');// create a new uservar newUser = User({  name: 'Peter Quill',  username: 'starlord55',  password: 'password',  admin: true});// save the usernewUser.save(function(err) {  if (err) throw err;  console.log('User created!');});

(Read)

There are many reasons for us to query our database of users. We'll need one specific user, all users, similar users, and many more scenarios. Here are a few examples:

我们查询用户数据库的原因很多。 我们将需要一个特定的用户,所有用户,相似的用户以及更多方案。 这里有一些例子:

找到所有 (Find All)

// get all the usersUser.find({}, function(err, users) {  if (err) throw err;  // object of all the users  console.log(users);});

找一个 (Find One)

// get the user starlord55User.find({ username: 'starlord55' }, function(err, user) {  if (err) throw err;  // object of the user  console.log(user);});

按编号查找 (Find By ID)

// get a user with ID of 1User.findById(1, function(err, user) {  if (err) throw err;  // show the one user  console.log(user);});

查询方式 (Querying)

You can also use MongoDB .

您还可以使用MongoDB 。

// get any admin that was created in the past month// get the date 1 month agovar monthAgo = new Date();monthAgo.setMonth(monthAgo.getMonth() - 1);User.find({ admin: true }).where('created_at').gt(monthAgo).exec(function(err, users) {  if (err) throw err;  // show the admins in the past month  console.log(users);});

更新资料 (Update)

Here we will find a specific user, change some attributes, and then re-save them.

在这里,我们将找到一个特定的用户,更改一些属性,然后重新保存它们。

获取用户,然后更新 (Get a User, Then Update)

// get a user with ID of 1User.findById(1, function(err, user) {  if (err) throw err;  // change the users location  user.location = 'uk';  // save the user  user.save(function(err) {    if (err) throw err;    console.log('User successfully updated!');  });});

Remember that since we created the function to change the updated_at date, this will also happen on save.

请记住,由于我们创建了用于更改updated_at日期的函数,因此save时也会发生这种情况。

查找和更新 (Find and Update)

An even easier method to use since we dont have to grab the user, modify, and then save. We are just issuing a mongodb findAndModify command.

一种更容易使用的方法,因为我们不必抓住用户,进行修改然后保存。 我们只是发出mongodb findAndModify命令。

// find the user starlord55// update him to starlord 88User.findOneAndUpdate({ username: 'starlord55' }, { username: 'starlord88' }, function(err, user) {  if (err) throw err;  // we have the updated user returned to us  console.log(user);});

按ID查找并更新 (Find By ID and Update)

// find the user with id 4// update username to starlord 88User.findByIdAndUpdate(4, { username: 'starlord88' }, function(err, user) {  if (err) throw err;  // we have the updated user returned to us  console.log(user);});

删除 (Delete)

获取用户,然后删除 (Get a User, Then Remove)

// get the user starlord55User.find({ username: 'starlord55' }, function(err, user) {  if (err) throw err;  // delete him  user.remove(function(err) {    if (err) throw err;    console.log('User successfully deleted!');  });});

查找和删除 (Find and Remove)

// find the user with id 4User.findOneAndRemove({ username: 'starlord55' }, function(err) {  if (err) throw err;  // we have deleted the user  console.log('User deleted!');});

按ID查找并删除 (Find By ID and Remove)

// find the user with id 4User.findByIdAndRemove(4, function(err) {  if (err) throw err;  // we have deleted the user  console.log('User deleted!');});

结论 (Conclusion)

Hopefully this will act as a good reference guide when using the mongoose package in Node.js and MongoDB applications.

希望当在Node.js和MongoDB应用程序中使用mongoose软件包时,这可以作为一个很好的参考指南。

翻译自:

转载地址:http://vjywd.baihongyu.com/

你可能感兴趣的文章
PHP Curl发送数据
查看>>
HTTP协议
查看>>
HTTPS
查看>>
git add . git add -u git add -A区别
查看>>
apache下虚拟域名配置
查看>>
session和cookie区别与联系
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Laravel框架学习笔记之任务调度(定时任务)
查看>>
浅析 Laravel 官方文档推荐的 Nginx 配置
查看>>
Swagger在Laravel项目中的使用
查看>>
Laravel 的生命周期
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
【2020-3-21】Mac安装Homebrew慢,解决办法
查看>>
influxdb 命令行输出时间为 yyyy-MM-dd HH:mm:ss(年月日时分秒)的方法
查看>>
jxl写入excel实现数据导出功能
查看>>