CRUD(增删改查)
CRUD为数据库的最常见的4种基本操作,即增加(Create)、读取(Retrieve)(重新得到数据)、更新(Update)和删除(Delete)几个单词的首字母简写。主要被用在描述软件系统中数据库或者持久层的基本操作功能。
mongoose提供如下的crud方法
- save
- find | findOne
- update
- remove
下面我们使用user模型为例,给出具体例子
增加(Create)
文档
Model#save(product,)
@description Saves this document.
Parameters:
- product, <function(err, > Number)} [fn] optional callback
Returns:
<Promise> Promise
具体代码
const user = new User({
username: 'i5ting',
password: '0123456789'
});
user.save((err, u) => {
t.false(err);
t.is(u.username, 'i5ting');
});
读取(Retrieve)
find:根据条件查询,返回的是数组
文档
Model.find(conditions, [fields], [options], [callback])
Finds documents
Parameters:
- conditions <Object>
- [fields] <Object> optional fields to select
- [options] <Object> optional
- [callback] <Function>
Returns:
<Query>
代码
User.find({}, (err, docs) => {
t.false(err);
t.is(docs.length, 1);
t.is(docs[0].username, 'i5ting');
});
findOne:根据条件查询,返回的是一条数据对象
文档
Model.findOne([conditions], [fields], [options], [callback])
Finds one document.
Parameters:
- [conditions] <Object>
- [fields] <Object> optional fields to select
- [options] <Object> optional
- [callback] <Function>
Returns:
<Query>
代码
User.findOne({username: 'i5ting'}, (err, doc) => {
t.false(err);
t.is(doc.length, 1);
t.is(doc.username, 'i5ting');
});
更新(Update)
findByIdAndUpdate:根据ID查找并更新
文档说明如下
Model.findByIdAndUpdate(id, [update], [options], [callback])
Issues a mongodb findAndModify update command by a documents id.
show code
Parameters:
- id <ObjectId, HexId> an ObjectId or string that can be cast to one.
- [update] <Object>
- [options] <Object>
- [callback] <Function>
Returns:
<Query>
具体代码
User.findByIdAndUpdate(u._id, {
username: 'sang',
}, (err, user) => {
t.false(err);
t.is(user.username, 'sang');
});
findOneAndUpdate:根据查询条件查找并更新
Model.findOneAndUpdate([conditions], [update], [options], [callback])
Issues a mongodb findAndModify update command.
Parameters:
- [conditions] <Object>
- [update] <Object>
- [options] <Object>
- [callback] <Function>
Returns:
<Query>
具体代码
User.findOneAndUpdate({
username: 'i5ting for update 2',
}, {
username: 'sang',
}, (err, user) => {
t.false(err);
t.is(user.username, 'sang');
});
删除(Delete)
文档
Model.remove(conditions, [callback])
Removes documents from the collection.
Parameters:
- conditions <Object>
- [callback] <Function>
Returns:
<Promise> Promise
代码
User.remove({username: 'i5ting for delete'}, (err, doc) => {
t.false(err);
t.is(doc.result.ok, 1);
t.is(doc.result.n, 1);
});
执行测试
$ cd db
$ npm test
> koa-db@1.0.0 test /Users/sang/workspace/17koa/book-source/db
> ava crud -v
数据库连接成功
✔ #save()
✔ #find() return array
✔ #findById() return array
✔ #findOne() return user obj
✔ #remove()
✔ #findByIdAndUpdate()
✔ #findOneAndUpdate()
6 tests passed
调试模式
调试模式是mongoose提供的一个非常实用的功能,用于查看mongoose模块对mongodb操作的日志,一般开发时会打开此功能,以便更好的了解和优化对mongodb的操作。
打开调试的核心代码是设置 debug
变量值为 true
即可
var mongoose = require("mongoose");
// 核心代码,是否开启测试
mongoose.set('debug', true);
var db = mongoose.connect("mongodb://127.0.0.1:27017/db_helloworld");
db.connection.on("error", function (error) {
console.log("数据库连接失败:" + error);
});
db.connection.on("open", function () {
console.log("数据库连接成功");
});
执行测试如下
$ cd db
$ npm test
> koa-db@1.0.0 test /Users/sang/workspace/17koa/book-source/db
> ava crud -v
数据库连接成功
Mongoose: users.remove({}) {}
✔ #save()
✔ #find() return array
✔ #findById() return array
✔ #findOne() return user obj
✔ #remove()
✔ #findByIdAndUpdate()
✔ #findOneAndUpdate()
Mongoose: users.insert({ username: 'i5ting', password: '0123456789', _id: ObjectId("5734490640caa6d36906b8d4"), __v: 0 })
Mongoose: users.find({}) { fields: undefined }
Mongoose: users.findOne({ username: 'i5ting' }) { fields: undefined }
Mongoose: users.insert({ username: 'i5ting for delete', password: '0123456789', _id: ObjectId("5734490640caa6d36906b8d5"), __v: 0 })
Mongoose: users.insert({ username: 'i5ting for update 1', password: '0123456789', _id: ObjectId("5734490640caa6d36906b8d6"), __v: 0 })
Mongoose: users.insert({ username: 'i5ting for update 2', password: '0123456789', _id: ObjectId("5734490640caa6d36906b8d7"), __v: 0 })
Mongoose: users.remove({ username: 'i5ting for delete' }) {}
Mongoose: users.findAndModify({ _id: ObjectId("5734490640caa6d36906b8d6") }) [] { '$set': { username: 'sang' } } { new: false, upsert: false }
Mongoose: users.findAndModify({ username: 'i5ting for update 2' }) [] { '$set': { username: 'sang' } } { new: false, upsert: false }
6 tests passed