CRUD(增删改查)

CRUD为数据库的最常见的4种基本操作,即增加(Create)、读取(Retrieve)(重新得到数据)、更新(Update)和删除(Delete)几个单词的首字母简写。主要被用在描述软件系统中数据库或者持久层的基本操作功能。

mongoose提供如下的crud方法

  • save
  • find | findOne
  • update
  • remove

下面我们使用user模型为例,给出具体例子

增加(Create)

文档

  1. Model#save(product,)
  2. @description Saves this document.
  3. Parameters:
  4. - product, <function(err, > Number)} [fn] optional callback
  5. Returns:
  6. <Promise> Promise

具体代码

  1. const user = new User({
  2. username: 'i5ting',
  3. password: '0123456789'
  4. });
  5. user.save((err, u) => {
  6. t.false(err);
  7. t.is(u.username, 'i5ting');
  8. });

读取(Retrieve)

find:根据条件查询,返回的是数组

文档

  1. Model.find(conditions, [fields], [options], [callback])
  2. Finds documents
  3. Parameters:
  4. - conditions <Object>
  5. - [fields] <Object> optional fields to select
  6. - [options] <Object> optional
  7. - [callback] <Function>
  8. Returns:
  9. <Query>

代码

  1. User.find({}, (err, docs) => {
  2. t.false(err);
  3. t.is(docs.length, 1);
  4. t.is(docs[0].username, 'i5ting');
  5. });

findOne:根据条件查询,返回的是一条数据对象

文档

  1. Model.findOne([conditions], [fields], [options], [callback])
  2. Finds one document.
  3. Parameters:
  4. - [conditions] <Object>
  5. - [fields] <Object> optional fields to select
  6. - [options] <Object> optional
  7. - [callback] <Function>
  8. Returns:
  9. <Query>

代码

  1. User.findOne({username: 'i5ting'}, (err, doc) => {
  2. t.false(err);
  3. t.is(doc.length, 1);
  4. t.is(doc.username, 'i5ting');
  5. });

更新(Update)

findByIdAndUpdate:根据ID查找并更新

文档说明如下

  1. Model.findByIdAndUpdate(id, [update], [options], [callback])
  2. Issues a mongodb findAndModify update command by a documents id.
  3. show code
  4. Parameters:
  5. - id <ObjectId, HexId> an ObjectId or string that can be cast to one.
  6. - [update] <Object>
  7. - [options] <Object>
  8. - [callback] <Function>
  9. Returns:
  10. <Query>

具体代码

  1. User.findByIdAndUpdate(u._id, {
  2. username: 'sang',
  3. }, (err, user) => {
  4. t.false(err);
  5. t.is(user.username, 'sang');
  6. });

findOneAndUpdate:根据查询条件查找并更新

  1. Model.findOneAndUpdate([conditions], [update], [options], [callback])
  2. Issues a mongodb findAndModify update command.
  3. Parameters:
  4. - [conditions] <Object>
  5. - [update] <Object>
  6. - [options] <Object>
  7. - [callback] <Function>
  8. Returns:
  9. <Query>

具体代码

  1. User.findOneAndUpdate({
  2. username: 'i5ting for update 2',
  3. }, {
  4. username: 'sang',
  5. }, (err, user) => {
  6. t.false(err);
  7. t.is(user.username, 'sang');
  8. });

删除(Delete)

文档

  1. Model.remove(conditions, [callback])
  2. Removes documents from the collection.
  3. Parameters:
  4. - conditions <Object>
  5. - [callback] <Function>
  6. Returns:
  7. <Promise> Promise

代码

  1. User.remove({username: 'i5ting for delete'}, (err, doc) => {
  2. t.false(err);
  3. t.is(doc.result.ok, 1);
  4. t.is(doc.result.n, 1);
  5. });

执行测试

  1. $ cd db
  2. $ npm test
  3. > koa-db@1.0.0 test /Users/sang/workspace/17koa/book-source/db
  4. > ava crud -v
  5. 数据库连接成功
  6. #save()
  7. #find() return array
  8. #findById() return array
  9. #findOne() return user obj
  10. #remove()
  11. #findByIdAndUpdate()
  12. #findOneAndUpdate()
  13. 6 tests passed

调试模式

调试模式是mongoose提供的一个非常实用的功能,用于查看mongoose模块对mongodb操作的日志,一般开发时会打开此功能,以便更好的了解和优化对mongodb的操作。

打开调试的核心代码是设置 debug 变量值为 true 即可

  1. var mongoose = require("mongoose");
  2. // 核心代码,是否开启测试
  3. mongoose.set('debug', true);
  4. var db = mongoose.connect("mongodb://127.0.0.1:27017/db_helloworld");
  5. db.connection.on("error", function (error) {
  6. console.log("数据库连接失败:" + error);
  7. });
  8. db.connection.on("open", function () {
  9. console.log("数据库连接成功");
  10. });

执行测试如下

  1. $ cd db
  2. $ npm test
  3. > koa-db@1.0.0 test /Users/sang/workspace/17koa/book-source/db
  4. > ava crud -v
  5. 数据库连接成功
  6. Mongoose: users.remove({}) {}
  7. #save()
  8. #find() return array
  9. #findById() return array
  10. #findOne() return user obj
  11. #remove()
  12. #findByIdAndUpdate()
  13. #findOneAndUpdate()
  14. Mongoose: users.insert({ username: 'i5ting', password: '0123456789', _id: ObjectId("5734490640caa6d36906b8d4"), __v: 0 })
  15. Mongoose: users.find({}) { fields: undefined }
  16. Mongoose: users.findOne({ username: 'i5ting' }) { fields: undefined }
  17. Mongoose: users.insert({ username: 'i5ting for delete', password: '0123456789', _id: ObjectId("5734490640caa6d36906b8d5"), __v: 0 })
  18. Mongoose: users.insert({ username: 'i5ting for update 1', password: '0123456789', _id: ObjectId("5734490640caa6d36906b8d6"), __v: 0 })
  19. Mongoose: users.insert({ username: 'i5ting for update 2', password: '0123456789', _id: ObjectId("5734490640caa6d36906b8d7"), __v: 0 })
  20. Mongoose: users.remove({ username: 'i5ting for delete' }) {}
  21. Mongoose: users.findAndModify({ _id: ObjectId("5734490640caa6d36906b8d6") }) [] { '$set': { username: 'sang' } } { new: false, upsert: false }
  22. Mongoose: users.findAndModify({ username: 'i5ting for update 2' }) [] { '$set': { username: 'sang' } } { new: false, upsert: false }
  23. 6 tests passed