一.mongodb学习准备
1.1First be sure you have MongoDB and Node.js installed.
1.1.1.官网下载mongodb,https://www.mongodb.com/
1.1.2.mongoose官网:https://mongoosejs.com/
二.mongoose Get Started
2.1.Next install Mongoose from the command line using npm
:
$ npm install mongoose
2.2.Now say we like fuzzy kittens and want to record every kitten we ever meet in MongoDB. The first thing we need to do is include mongoose in our project and open a connection to the test
database on our locally running instance of MongoDB
在项目中引入mongoose,并打开连接到test数据库(如果数据库中没有test,那么mongo会自动创建)
// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
2.3.We have a pending connection to the test database running on localhost. We now need to get notified if we connect successfully or if a connection error occurs:
因为本地test数据库与本地有挂起连接,我们需要去知道连接成功或者失败;
注意:这里是使用on()和once()方法
Once our connection opens, our callback will be called.
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
//如果连接成功,回调函数将会执行
});
2.4.With Mongoose, everything is derived from a Schema. Let's get a reference to it and define our kittens.
mongoose的对象来自于Schema
var kittySchema = new mongoose.Schema({
name: String
});
2.5.So far so good. We've got a schema with one property, name
, which will be a String
. The next step is compiling our schema into a Model.
通过model获取对象
var Kitten = mongoose.model('Kitten', kittySchema);
三.Demo
3.1在project下创建libs文件夹,libs下创建user.js
/*
* @author: lansir
* @date" 2018/10/4
* @description go~js!
*/
//1.引入mongoose
const mongoose = require('mongoose');
//2.通过Schema获取mongoose对象
const schema = mongoose.Schema({
name:String,
age:Number,
hobby:[String]
});
//3.将mongoose对象转换为model,并导出(module.exports)
module.exports = mongoose.model('users',schema);
3.2在project下创建js
/*
* @author: lansir
* @date" 2018/10/4
* @description go~js!
*/
let mongoose = require('mongoose');//1.引入mongoose
//2.引入libs下面的user,获取model对象User.User可以直接调用mongoose中的CRUD方法!!!
const User = require('./model/user');
//include mongoose in our project
//and open a connection to the test database on our locally running instance of MongoDB.
mongoose.connect('mongodb://localhost/test');//3.mongoose与本地连接
//We have a pending connection to the test database running on localhost.
// We now need to get notified if we connect successfully or if a connection error occurs:
const db = mongoose.connection;//4.获取连接对象
//连接对象db监听连接成功与否
db.on('error',(err)=>{
console.log(err);
});
//连接对象监听是否已连接
db.once('open',()=>{
console.log('mongodb connect well');
//连接成功,执行insert()方法
insert()
});
//向数据库中插入数据的方法
async function insert() {
const result = await User.create({
name:'咚咚锵',
age:18,
hobby:['游泳','跑步']
});
console.log(result);
}
网友评论