mongoose的一个实例

来源:互联网 发布:光荣使命手游巨人网络 编辑:程序博客网 时间:2024/06/03 22:03

mongoose是node.js的一个库,提供了mongoDB对象,映射到ORM(Object Relational Mapping),ORM和ODM,就是mongoose从数据库中编译数据到js对象中以应用在自己的应用中,下面开始如何一步一步创建一个数据库并存储数据。(假设你已经安装了node.js和MongoDB,并确保你的mongodb已经running).

一,连接MongoDB
在这篇文章我们将会连接到一个名为test的默认数据库。而且我们也需要确定任何连接错误都打印在命令行中。

var mongoose = require('mongoose');var db = mongoose.connection;db.on('error', console.error);db.once('open', function() {  // Create your schemas and models here.});mongoose.connect('mongodb://localhost/test');

2.创建Schemas and Models

开始,为了处理数据,我们需要一个Schema和一个model,它们会一直在mongodb数据库中。Scheams用来定义文档数据结构,models用来创建存储数据实例。下面代码示例

var movieSchema = new mongoose.Schema({  title: { type: String }, rating: String, releaseYear: Number, hasCreditCookie: Boolean});// Compile a 'Movie' model using the movieSchema as the structure.// Mongoose also creates a MongoDB collection called 'Movies' for these documents.var Movie = mongoose.model('Movie', movieSchema);

3.Create, Retrieve, Update, and Delete (CRUD)

如果已经定义了一个model,那么创建一个新的Movie文件非常容易,仅仅是实例化movie这个model。示例代码:

var thor = new Movie({  title: 'Thor', rating: 'PG-13', releaseYear: '2011'  // Notice the use of a String rather than a Number - Mongoose will automatically convert this for us., hasCreditCookie: true});thor.save(function(err, thor) {  if (err) return console.error(err);  console.dir(thor);});

这个save的方法会提供最新的创建文件,可以通过console.log查看

{  "title": "Thor",  "rating": "PG-13",  "releaseYear": 2011,  "hasCreditCookie": true,  "_id": "519a979e918d4d0000000001",  "__v": 0}

检索数据库中的数据有多种方法,通过findOne只返回一条数据

// Find a single movie by name.Movie.findOne({ title: 'Thor' }, function(err, thor) {  if (err) return console.error(err);  console.dir(thor);});// Find all movies.Movie.find(function(err, movies) {  if (err) return console.error(err);  console.dir(movies);});// Find all movies that have a credit cookie.Movie.find({ hasCreditCookie: true }, function(err, movies) {  if (err) return console.error(err);  console.dir(movies);});

mongoose也可以封装一个函数供以后使用

movieSchema.statics.findAllWithCreditCookies = function(callback) {  return this.find({ hasCreditCookie: true }, callback);};// Use the helper as a static function of the compiled Movie model.Movie.findAllWithCreditCookies(function(err, movies) {  if (err) return console.error(err);  console.dir(movies);});

原文在此:http://blog.modulus.io/getting-started-with-mongoose

0 0
原创粉丝点击