2018-12-20 基于填字格小程序后台笔记:安装依赖Mongoose
mongodb是非关系型数据库,所有的操作依赖于model。
这次在nodejs项目中使用,快速上手,我的总结就是:连接成功,建立model,使用model操作数据。详情见下文——
// 安装 mongoose依赖
npm install mongoose -save
// 引入依赖
const mongoose = require('mongoose')
1. 连接数据库:
标准的url格式 (Standard Connection String Format):
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
<语法> 两种方式连接数据库,url格式及意义
mongodb://r1.example.net:27017,r2.example.net:27017/
// 连接语法
mongoose.connect(uri(s), [options], [options.useMongoClient], [callback])
mongoose.connect(uri, options, function(error) {
});
// Or using promises
mongoose.connect(uri, options).then(
() => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
err => { /** handle initial connection error */ }
);
连接示例
mongoose.connect('mongodb://localhost/test', (err)=>{
console.warn('数据库连接失败:'+err);
}); // 连接本地数据库,默认端口号是27017,数据库是test
或者
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
});
2. 使用schema:
在Mongoose中所有的操作都依赖于Schema,每个Schema与数据库中的一个collection匹配,并且,定义了这个collection中的documents。
(Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection)
<语法> 生成一个schema实例
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
let blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
Schema允许的SchemaTypes:String、Number、Date、Buffer、Boolean、Mixed、ObjectId、Array、Decimal128、Map
<语法>Schema.prototype.add() :添加key path/ schema type pairs
const blogSchema = new Schema();
blogSchema.add({ name: 'string', color: 'string', price: 'number' });
// 复制一个实例
const TurboManSchema = new Schema();
blogSchema.add(ToySchema).add({ year: Number });
3 生成model
Models 是从 Schema 编译来的构造函数。 它们的实例就代表着可以从数据库保存和读取的 documents。 从数据库创建和读取 document 的所有操作都是通过 model 进行的。
<语法> 生成model
var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);
第一个参数是跟 model 对应的集合( collection )名字的 单数 形式。 Mongoose 会自动找到名称是 model 名字 复数 形式的 collection 。 对于上例,Tank 这个 model 就对应数据库中 tanks 这个 collection。.model() 这个函数是对 schema 做了拷贝(生成了 model)。 你要确保在调用 .model() 之前把所有需要的东西都加进 schema 里了。
// 输出model
module.exports.tank = mongoose.model([tanks,] 'tank', schema);
注意:‘tank’ 这里必须与输出的名字相同,否则会出现问题。
4 用到的操作语法
-_id转id
mongodb中会自动生成_id(ObjectId),在与前端合作的时候,为了符合习惯要改成id在生成model时,为model添加以下方法,然后对查询出来的每一个document使用toClient()方法;
tank.method('toClient', function () {
var obj = this.toObject();
obj.id = obj._id.toString();
delete obj._id;
return obj;
});
-查询排序
取出isDeleted字段不等1的时候,从pos开始的按照_id从大到小的顺序取limit条document中的_id和content字段,
const docs = await question.find({ isDeleted: { $ne: 1 } }, '_id content')
.skip(pos)
.limit(limit)
.sort({ '_id': -1 })
- 批量插入
await question.insertMany( [
{"content":"你今天开心吗?"},
{"content":"你最爱的是周杰伦吗"}
]
)
- 改
model.updateOne(conditions, docs)
await baikeEntry.updateOne({ _id: id }, { $set: { tips: tips, name: name } })
- 数组操作:添加
向 tag数组中添加一个元素
await baikeEntry.updateOne({ _id: id }, { $push: { tag: "customize" } })
-数据操作:删除
删除字段数组tag中的指定的"customize" :tag:[“customize” ,0,‘p’]=>tag[0,‘p’]
await baikeEntry.updateOne({ _id: id }, { $pull: { tag: "customize" } },