Mongoose入门介绍
发布于 14 年前 作者 xuanhou 23284 次浏览 最后一次编辑是 8 年前

<blockquote>什么是Mongoose?</blockquote> <br/><a href=“https://github.com/LearnBoost/mongoose”>Mongoose</a>是基于<a href=“https://github.com/christkv/node-mongodb-native”>node-mongodb-native</a>开发的MongoDB nodejs驱动,可以在异步的环境下执行。 <br/><blockquote> <br/><p style=“text-align: left;”>如何安装Mongoose?</p> <br/></blockquote> <br/><p style=“text-align: left;”><em>npm install mongoose</em></p> <br/> <br/><blockquote>如何使用Mongoose?</blockquote> <br/><ul> <br/> <li>test.js代码:</li> <br/></ul> <br/><pre escaped=“true” lang=“javascript” line=“1”>var mongoose = require(‘mongoose’) <br/> , Schema = mongoose.Schema <br/> <br/>mongoose.connect(‘mongodb://localhost/test’); <br/> <br/>var TestSchema = new Schema({ <br/> user_id : {type : Number, index : true} <br/> ,username : {type : String} <br/>}); <br/> <br/>var model_name = coll_name = ‘taobao’; <br/>mongoose.model(model_name, TestSchema, coll_name); <br/> <br/>var TAOBAO = mongoose.model(model_name, coll_name); <br/>var taobao = new TAOBAO(); <br/>taobao.user_id = 1; <br/>taobao.username = ‘xuanhou’; <br/>taobao.save(function(err) { <br/> if (err) { <br/> console.log(‘save failed’); <br/> } <br/> console.log(‘save success’); <br/>});</pre> <br/><ul> <br/> <li>执行test.js</li> <br/></ul> <br/><em>node test.js</em> <br/><ul> <br/> <li>查看是否执行成功:</li> <br/></ul> <br/><pre escaped=“true” lang=“javascript” line=“1”>[xuanhou.ysh@XXXX test]$ mongo <br/>MongoDB shell version: 1.8.0 <br/>connecting to: test <br/>> show collections <br/>system.indexes <br/>taobao <br/>> db.taobao.find() <br/>{ “_id” : ObjectId(“4db65fafcb4312401d000001”), “user_id” : 1, “username” : “xuanhou” } <br/>> exit <br/>bye</pre> <br/><blockquote>为什么还要基于node-mongodb-native开发mongoose呢?</blockquote> <br/>下面是node-mongodb-native实现的代码相信能让你了解为什么很多人选择Mongoose(callback层数太多): <br/><pre escaped=“true” lang=“javascript” line=“1”> <br/> <br/>var client = new Db(‘integration_tests_20’, new Server(“127.0.0.1”, 27017, {})); <br/> client.open(function(err, p_client) { <br/> client.createCollection(‘test_insert’, function(err, collection) { <br/> client.collection(‘test_insert’, function(err, collection) { <br/> for(var i = 1; i < 1000; i++) { <br/> collection.insert({c:1}, function(err, docs) {}); <br/> } <br/> <br/> collection.insert({a:2}, function(err, docs) { <br/> collection.insert({a:3}, function(err, docs) { <br/> collection.count(function(err, count) { <br/> test.assertEquals(1001, count); <br/> // Locate all the entries using find <br/> collection.find(function(err, cursor) { <br/> cursor.toArray(function(err, results) { <br/> test.assertEquals(1001, results.length); <br/> test.assertTrue(results[0] != null); <br/> <br/> // Let’s close the db <br/> client.close(); <br/> }); <br/> }); <br/> }); <br/> }); <br/> }); <br/> }); <br/> }); <br/> }); <br/></pre> <br/><blockquote>目前Mongoose的开发情况如何?</blockquote> <br/>Mongoose已经实现了大部分功能,但还有些Mongodb提供的feature没有实现,所以也给使用者提供了打补丁的机会,下面是我最近给Mongoose打的两个补丁: <br/><ul> <br/> <li>让mongoose支持distinct操作</li> <br/></ul> <br/><pre escaped=“true” lang=“javascript” line=“1”>Index: model.js <br/>=================================================================== <br/>— model.js (revision 12218) <br/>+++ model.js (working copy) <br/>@@ -492,6 +492,34 @@ <br/>}; <br/> <br/>/** <br/>+ * distinct values for key <br/>+ * <br/>+ * @param {String} key <br/>+ * @param {Object} conditions <br/>+ * @param {Function} optional callback <br/>+ * @api public <br/>+ / <br/>+ <br/>+Model.distinct = function (key, conditions, callback) { <br/>+ if (‘function’ == typeof conditions) { <br/>+ callback = conditions; <br/>+ conditions = {}; <br/>+ } <br/>+ var query = new Query(conditions, key).bind(this, ‘distinct’); <br/>+ if (‘undefined’ == typeof callback) <br/>+ return query; <br/>+ var cQuery; <br/>+ if (cQuery = this._cumulativeQuery) { <br/>+ merge(query._conditions, cQuery._conditions); <br/>+ if (query.options && cQuery.options) <br/>+ merge(query.options, cQuery.options); <br/>+ delete this._cumulativeQuery; <br/>+ } <br/>+ if (!query.model) query.bind(this, ‘distinct’); <br/>+ return query.distinct(callback); <br/>+}; <br/>+ <br/>+/* <br/>* where enables a very nice sugary api for doing your queries. <br/>* For example, instead of writing: <br/>* User.find({age: {$gte: 21, $lte: 65}}, callback);</pre> <br/><pre escaped=“true” lang=“javascript” line=“1”>Index: query.js <br/>=================================================================== <br/>— query.js (revision 12218) <br/>+++ query.js (working copy) <br/>@@ -11,6 +11,10 @@ <br/> <br/>function Query (criteria, options) { <br/>options = this.options = options || {}; <br/>+ if (‘string’ == typeof options) { <br/>+ this._key = options; <br/>+ options = this.options = {}; <br/>+ } <br/>this.safe = options.safe <br/>this._conditions = {}; <br/>if (criteria) this.find(criteria); <br/>@@ -730,6 +734,24 @@ <br/>}; <br/> <br/>/** <br/>+ * Casts this._conditions and sends a distinct <br/>+ * command to mongodb. Invokes a callback upon <br/>+ * receiving results. <br/>+ * <br/>+ * @param {Function} callback fn(err, cardinality) <br/>+ * @api public <br/>+ / <br/>+Query.prototype.distinct = function (callback) { <br/>+ this.op = ‘distinct’; <br/>+ var model = this.model; <br/>+ this.cast(model); <br/>+ var castQuery = this._conditions; <br/>+ var key = this._key; <br/>+ model.collection.distinct(key, castQuery, callback); <br/>+ return this; <br/>+}; <br/>+ <br/>+/* <br/>* Casts the query, sends the update command to mongodb. <br/>* If there is an error, the callback handles it. Otherwise, <br/>* we just invoke the callback whereout passing it an error.</pre> <br/><ul> <br/> <li>让$gt/$gte/$lt/$lte等操作支持字符串参数</li> <br/></ul> <br/><pre escaped=“true” lang=“javascript” line=“1”>Index: string.js <br/>=================================================================== <br/>— string.js (revision 12218) <br/>+++ string.js (working copy) <br/>@@ -139,10 +139,15 @@ <br/>} <br/> <br/>SchemaString.prototype.$conditionalHandlers = { <br/>- ‘$ne’: handleSingle <br/>+ ‘$lt’: handleSingle <br/>+ , ‘$lte’: handleSingle <br/>+ , ‘$gt’: handleSingle <br/>+ , ‘$gte’: handleSingle <br/>+ , ‘$ne’: handleSingle <br/>, ‘$in’: handleArray <br/>, ‘$nin’: handleArray <br/>}; <br/>+ <br/>SchemaString.prototype.castForQuery = function ($conditional, val) { <br/>var handler; <br/>if (arguments.length === 2) {</pre>

9 回复

通过 mongoose 能不能把一个文件存到mongodb数据库中去,希望大家提供思路!!!

我目前是写了一个nodejs负责将CSV文件中的内容导入到mongodb中去的。 <br/> <br/>1)生成CSV文件(mysql数据库导出的数据) <br/>2)NodeJs每次读一行,然后分割为很多个fields,然后调用save将这些field组成的document插入到mongodb中 <br/>3)读取文件结束,关闭连接

mongoose是一个orm,如果只是想简单的读写,不需要定义schema和验证,可以方便的使用mongoq <br/> https://github.com/zzdhidden/mongoq

[…] http://cnodejs.org/blog/?p=824 此条目发表在 未分类 分类目录,贴了 mongodb, mongoose, 学习 […]

[…] http://cnodejs.org/blog/?p=824 此条目发表在 转载 分类目录,贴了 mongodb, mongoose, 学习 […]

你实现mongoose存取文件了吗 存文件就是将文件转成字节流然后存进去 我现在不知道怎么取出来

层数太多那个例子,貌似和node-mongodb-native没关吧?

关于第一个例子: helomongoose.model(model_name, TestSchema, coll_name); var TAOBAO = mongoose.model(model_name, coll_name);

为什么这样写? 表示不是很明白。可以这样吗?

var TAOBAO  = mongoose.model(model_name, TestSchema, coll_name);
回到顶部