1 安装 moogoose 模块 ,附加 --save 参数将包的信息添加到package.json 文件
npm install --save moogoose
2 加载 moogoose 模块,并连接数据库
var mongoose = require(‘mongoose‘); //mongoose.connect(‘mongodb://mongod所在地址ip(ipdress)/需要连接的数据库名(databasename)‘); mongoose.connect(‘mongodb://localhost/news‘);
3 建模(结构)
var newsSchema = mongoose.Schmea({ title:String type:Numer category:Array ... : .... });
4 把Schema编译转化成modal(此时的modal是一个类)
newsModel = mongoose.model(‘news‘,newsSchema)
5 我们可以实例化这个类并进行一些操作
var news = new newsModel({title:"This is a title","type":1,"category":[{category_id:"1","category_name":"国内"}]}); console.log(news.title); // This is a title
我们也可以给schema 添加 方法, 添加的方法需要在编译成modal之前
newsSchema.methods.say = function(){ console.log ("It is a method to show the title : " + this.title); } newsModel = mongoose.model(‘news‘,newsSchema); // 实例化并调用 var news = new newsModel({title:"This is a title","type":1,"category":[{category_id:"1","category_name":"国内"}]}); news.say(); // 输出 : It is a method to show the title : This is a title
6 前面的话,我们都在讲给schema添加方法,编译之后,对创建出来的modal进行实例化,既然是数据库,少不了保存、查询等操作啦。
var news = new newsModel({title:"This is a title","type":1,"category":[{category_id:"1","category_name":"国内"}]}); news.save(function(error,result){ if(error){ console.log(error); }else{ console.log(result); } });
时间: 2024-10-09 19:37:30