程序员代码笔记

Node后台|数据库的安装及使用(简版)

2018-05-30  本文已影响22人  贝一平

MAC 安装mongoDB

brew install mongodb

启动 mongoDB

./mongod --dbpath /data/mongodbdata

判断mongoDB是否已经开启

netstat -lanp | grep "27017"

关闭 mongoDB的服务

service mongod stop

mongodb启动成功后会显示

 waiting for connections on port 27017

然后我们去看看node如何连接mongodb
node 连接mongoDB需要用到 mongoose

npm install mongoose --save
const mongoose = require('mongoose');
mongoose.connect('mongodb://xxx.xxx.xxx');

如果连接成功的话会出现

2018-05-29T17:23:53.595+0800 I NETWORK  [initandlisten] connection accepted from xxx.xxx.xxx#1 (1 connection now open)

数据库相关操作

查看当前使用的数据库

db

切换数据库

use dbName //无则创建

查看所有的数据库列表

show dbs //但是这个你只能看到local,不管你通过use创建了多少个数据库 

创建集合

db.createCollection("users")
//结果 { "ok" : 1 }

经过上面这个创建collection再执行命令show dbs,你就会发现刚刚使用use创建的库出现了,因为使用命令“use 数据库名称”,只是标记你要创建新的数据库,但是实际没有任何数据写入,所以mongodb是不会真的创建数据库的。

查看已有的集合(表)

show collections

集合中插入文档数据

db.collectionsName.insert({……})

查询表中所有的数据

db.collectionName.find()

更新表数据

db.collectionName.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}},{multi:true})

其他操作因暂时不涉及,如日后涉及到会在此处更新

Moogse操作数据库

首先添加一条数据

别的不说,先上代码找找自信

// 首先先学着给集合里添加数据验证
//(虽然我想说表结构但是想想可能说校验比较合适)
//定义Schema相当于定义了一个表结构
var usersSchema = mongoose.Schema({
  name: String
});

//这一步:将校验(Schema)和表(collection)关联器来
var Users = mongoose.model('Users', usersSchema);

//新数据
var tom = new Users({ name: 'tom' });
console.log(tom.name); 

//插入数据
tom.save(function (err, res) {
  if (err) return console.error(err);
  console.log(res)
});

为什么我说Schema像是数据校验
因为当我们把新数据改成如下

var tom = new Users({ name: {test:"name"} });

是会报错的,报错片段如下

{ ValidationError: Users validation failed: name: Cast to String failed for value "{ test: 'name' }" at path "name"

但是如果,你把它写成数组,又会转换成字符串"3,4"。当然Schema不仅仅就完成一个类似校验的功能,这里为了方便理解,我只是简单做了个比喻。

var tom = new Users({ name: [3,4] });

至于剩下的涉及到的什么增删改查之类的操作,用到时就自己翻翻手册吧。

上一篇 下一篇

猜你喜欢

热点阅读