孤独的灵魂漂浮在黑暗上 發表於 2016-3-23 18:44:00

Nodejs学习笔记(十四)— Mongoose介绍和入门

<style>.wilson_body { color: rgba(0, 0, 0, 1); font-family: 微软雅黑, PTSans, Arial, sans-serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: normal; line-height: 110% }
.wilson_body img { padding: 2px; border: 3px solid rgba(242, 245, 244, 1) }
#menu ul { list-style: square }
#menu li { margin: 10px auto }
.wilson_quote { font-style: italic; color: rgba(0, 204, 255, 1); text-decoration: none }
.wilson_body a { color: rgba(0, 204, 255, 1); text-decoration: none }
.wilson_body a:hover { color: rgba(0, 204, 255, 1); text-decoration: underline; background-color: rgba(138, 136, 136, 1) }
.wilson_highlight { color: rgba(0, 204, 255, 1); font-family: 黑体; font-size: 16px; font-weight: lighter }
.wilson_h1 { background: rgba(138, 136, 136, 1); border-radius: 6px !important; box-shadow: 0 0 1px rgba(224, 224, 224, 1), 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: rgba(255, 255, 255, 1); font-family: 微软雅黑, 宋体, 黑体, Arial; font-size: 18px; font-weight: bold; height: 25px; line-height: 25px; margin: 16px 0 !important; padding: 5px 0 5px 20px; text-shadow: 2px 2px 3px rgba(34, 34, 34, 1) }
.wilson_tip { color: rgba(255, 0, 0, 1); font-family: 黑体; font-style: italic; font-weight: 500 }
.wilson_body table { padding: 0; margin-left: 20px }
.wilson_body table th { font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif; color: rgba(79, 107, 114, 1); border-right: 1px solid rgba(193, 218, 215, 1); border-bottom: 1px solid rgba(193, 218, 215, 1); border-top: 1px solid rgba(193, 218, 215, 1); letter-spacing: 2px; text-transform: uppercase; text-align: left; padding: 6px 6px 6px 14px; background: no-repeat rgba(202, 232, 234, 1) }
.wilson_body table th.nobg { border-top: 0; border-left: 0; border-right: 1px solid rgba(193, 218, 215, 1); background: none }
.wilson_body table td { border-right: 1px solid rgba(193, 218, 215, 1); border-bottom: 1px solid rgba(193, 218, 215, 1); background: rgba(255, 255, 255, 1); font-size: 14px; padding: 6px 6px 6px 14px; color: rgba(79, 107, 114, 1) }
.wilson_dl_img { width: 30px; height: 30px }
.wilson_dl_text { float: left }</style>
<div class="wilson_body">
<h1 class="wilson_h1">目录</h1>
<div id="menu">
<ul>
<li>简介</li>
<li>mongoose安装</li>
<li>连接字符串</li>
<li>Schema</li>
<li>Model</li>
<li>常用数据库操作
<ul>
<li>插入</li>
<li>更新</li>
<li>删除</li>
<li>条件查询</li>
<li>数量查询</li>
<li>根据_id查询</li>
<li>模糊查询</li>
<li>分页查询</li>
</ul>
</li>
<li>其它操作</li>
<li>写在之后...</li>
</ul>
</div>
<h1 id="node_intro" class="wilson_h1">简介</h1>
<p>  Mongoose是在node.js异步环境下对mongodb进行便捷操作的对象模型工具</p>
<p>  那么要使用它,首先你得装上node.js和mongodb,关于mongodb的安装和操作介绍可以参考:http://www.cnblogs.com/zhongweiv/p/node_mongodb.html</p>
<p>&nbsp;</p>
<p>  Github地址:https://github.com/Automattic/mongoose</p>
<p>  API Docs:http://mongoosejs.com/docs/guide.html</p>
<p>&nbsp;</p>
<p>  前面有介绍过用node-mongodb-native来操作mongodb,实际开发中估计更多会选用类似mongoose的模块来操作来提升开发效率</p>
<p>&nbsp;</p>
<p>  下面我们一步步来了解mongoose的基本操作^_^!</p>
<p>&nbsp;</p>
<h1 id="mg_install" class="wilson_h1">mongoose安装</h1>
<div class="cnblogs_code">
<pre>npm <span style="color: rgba(0, 0, 255, 1)">install</span> mongoose</pre>
</div>
<p>  安装成功后如下图:</p>
<blockquote>
<p><img src="https://images.cnblogs.com/cnblogs_com/zhongweiv/804376/o_1.png" alt="" width="810" height="341"></p>
</blockquote>
<p>  安装成功后,就可以通过&nbsp;require('mongoose') 来使用!</p>
<p>&nbsp;</p>
<h1 id="mg_connstr" class="wilson_h1">连接字符串</h1>
<p>  创建一个db.js</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> mongoose = require('mongoose'<span style="color: rgba(0, 0, 0, 1)">),
    DB_URL </span>= 'mongodb://localhost:27017/mongoosesample'<span style="color: rgba(0, 0, 0, 1)">;

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 连接
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
mongoose.connect(DB_URL</span><span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 连接成功
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
mongoose.connection.on(</span>'connected', <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> () {   
    console.log(</span>'Mongoose connection open to ' +<span style="color: rgba(0, 0, 0, 1)"> DB_URL);
});   

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 连接异常
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
mongoose.connection.on(</span>'error',<span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> (err) {   
    console.log(</span>'Mongoose connection error: ' +<span style="color: rgba(0, 0, 0, 1)"> err);
});   

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 连接断开
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
mongoose.connection.on(</span>'disconnected', <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> () {   
    console.log(</span>'Mongoose connection disconnected'<span style="color: rgba(0, 0, 0, 1)">);
});    </span></pre>
</div>
<p>  调用node db.js执行就会看到输出如下图</p>
<blockquote>
<p><img src="https://images.cnblogs.com/cnblogs_com/zhongweiv/804376/o_3.png" alt="" width="810" height="120"></p>
</blockquote>
<p>  从代码中可以看出,监听了几个事件,并且执行触发了connected事件,这表示连接成功</p>
<p>  connection中不止有如上几个事件,关键看你想要监听哪个事件。</p>
<p>&nbsp;</p>
<p>  其它事件可以自行查看:http://mongoosejs.com/docs/api.html#connection_Connection</p>
<p>  </p>
<p>  这是最简单的连接字符串,当然还有其它形式,比如:连接密码、数据库连接设置、集群方式连式等等,这里解释了,用着了时候自行查询API文档</p>
<p>  http://mongoosejs.com/docs/api.html#index-js</p>
<p>  </p>
<h1 id="mg_schema" class="wilson_h1">Schema</h1>
<p>  schema是mongoose里会用到的一种数据模式,可以理解为表结构的定义;每个schema会映射到mongodb中的一个collection,它不具备操作数据库的能力</p>
<p>  我们先改造一下db.js,导出mongoose对象  </p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> mongoose = require('mongoose'<span style="color: rgba(0, 0, 0, 1)">),
    DB_URL </span>= 'mongodb://localhost:27017/mongoosesample'<span style="color: rgba(0, 0, 0, 1)">;

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 连接
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
mongoose.connect(DB_URL);

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 连接成功
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
mongoose.connection.on(</span>'connected', <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> () {   
    console.log(</span>'Mongoose connection open to ' +<span style="color: rgba(0, 0, 0, 1)"> DB_URL);
});   

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 连接异常
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
mongoose.connection.on(</span>'error',<span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> (err) {   
    console.log(</span>'Mongoose connection error: ' +<span style="color: rgba(0, 0, 0, 1)"> err);
});   

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 连接断开
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
mongoose.connection.on(</span>'disconnected', <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> () {   
    console.log(</span>'Mongoose connection disconnected'<span style="color: rgba(0, 0, 0, 1)">);
});   

<span style="color: rgba(255, 0, 0, 1)">module.exports </span></span><span style="color: rgba(255, 0, 0, 1)">= mongoose;</span></pre>
</div>
<p>  下面我们定义一个user的Schema,命名为user.js</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 用户信息
</span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">var</span> mongoose = require('./db.js'<span style="color: rgba(0, 0, 0, 1)">),
    Schema </span>=<span style="color: rgba(0, 0, 0, 1)"> mongoose.Schema;

</span><span style="color: rgba(0, 0, 255, 1)">var</span> UserSchema = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Schema({         
    username : { type: String },                  </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户账号</span>
    userpwd: {type: String},                        <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    userage: {type: Number},                        <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">年龄</span>
    logindate : { type: Date}                     <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">最近登录时间</span>
<span style="color: rgba(0, 0, 0, 1)">});<br></span></pre>
</div>
<p>  定义一个Schema就这么简单,指定字段名和类型</p>
<p>  Schema Types内置类型如下:</p>
<p><span style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1)"><em>  String</em></span></p>
<p><span style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1)"><em>  Number</em></span></p>
<p><span style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1)"><em>  Boolean | Bool</em></span></p>
<p><span style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1)"><em>  Array</em></span></p>
<p><span style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1)"><em>  Buffer</em></span></p>
<p><span style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1)"><em>  Date</em></span></p>
<p><span style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1)"><em>  ObjectId | Oid</em></span></p>
<p><span style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1)"><em>  Mixed</em></span></p>
<p>&nbsp;</p>
<p><span class="wilson_tip">  Schema中还可以做一些常用事,后面再讲!</span></p>
<p>&nbsp;</p>
<h1 id="mg_model" class="wilson_h1">Model</h1>
<p>  定义好了Schema,接下就是生成Model。</p>
<p>  model是由schema生成的模型,可以对数据库的操作</p>
<p>  我们对上面的定义的user的schema生成一个User的model并导出,修改后代码如下</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 用户信息
</span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">var</span> mongoose = require('./db.js'<span style="color: rgba(0, 0, 0, 1)">),
    Schema </span>=<span style="color: rgba(0, 0, 0, 1)"> mongoose.Schema;

</span><span style="color: rgba(0, 0, 255, 1)">var</span> UserSchema = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Schema({         
    username : { type: String },                  </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户账号</span>
    userpwd: {type: String},                        <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    userage: {type: Number},                        <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">年龄</span>
    logindate : { type: Date}                     <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">最近登录时间</span>
<span style="color: rgba(0, 0, 0, 1)">});

<span style="color: rgba(255, 0, 0, 1)">module.exports </span></span><span style="color: rgba(255, 0, 0, 1)">= mongoose.model('User',UserSchema);</span></pre>
</div>
<p>&nbsp;</p>
<h1 id="mg_op" class="wilson_h1">常用数据库操作</h1>
<p>  接下来创建一个test.js文件做一些常用操作演示。</p>
<p><strong>  插入</strong></p>
<p><strong>  </strong><em><span style="color: rgba(0, 204, 255, 1)">Model#save()</span></em></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 插入
</span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> insert() {

    </span><span style="color: rgba(0, 0, 255, 1)">var</span> user = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> User({
      username : </span>'Tracy McGrady',               <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户账号</span>
      userpwd: 'abcd',                            <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
      userage: 37,                              <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">年龄</span>
      logindate : <span style="color: rgba(0, 0, 255, 1)">new</span> Date()                      <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">最近登录时间</span>
<span style="color: rgba(0, 0, 0, 1)">    });

    user.<span style="color: rgba(255, 0, 0, 1)">save</span>(</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> (err, res) {

      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }

    });
}

insert();</span></pre>
</div>
<p>  结果在robmongo工具中查看</p>
<blockquote>
<p><img src="https://images.cnblogs.com/cnblogs_com/zhongweiv/804376/o_5.png" alt="" width="785" height="275"></p>
</blockquote>
<p>  从图中可以看到插入成功! </p>
<p>&nbsp;</p>
<p>  <strong>更新</strong>&nbsp;</p>
<p><span style="color: rgba(0, 204, 255, 1)"><em>  Model.update(conditions, update, , )</em></span></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> update(){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> wherestr = {'username' : 'Tracy McGrady'<span style="color: rgba(0, 0, 0, 1)">};
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> updatestr = {'userpwd': 'zzzz'<span style="color: rgba(0, 0, 0, 1)">};
   
    User.<span style="color: rgba(255, 0, 0, 1)">update</span>(wherestr, updatestr, </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(err, res){
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }
    })
}

update();</span></pre>
</div>
<p>  根据用户名更新密码,执行后结果如图</p>
<blockquote>
<p><img src="https://images.cnblogs.com/cnblogs_com/zhongweiv/804376/o_7.png" alt="" width="785" height="275"></p>
</blockquote>
<p>  图中可以看出,密码更新成功!<span style="color: rgba(255, 0, 0, 1)"><span style="color: rgba(0, 0, 0, 1)">update</span></span>方法基本可以满足所有更新!</p>
<p>  </p>
<p>  常用方法还有findByIdAndUpdate,这种比较有指定性,就是根据_id</p>
<p><em><span style="color: rgba(0, 204, 255, 1)">  Model.findByIdAndUpdate(id, , , )</span></em></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> findByIdAndUpdate</span><span style="color: rgba(0, 0, 0, 1)">(){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> id = '56f2558b2dd74855a345edb2'<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> updatestr = {'userpwd': 'abcd'<span style="color: rgba(0, 0, 0, 1)">};
   
    User.<span style="color: rgba(255, 0, 0, 1)">findByIdAndUpdate</span>(id, updatestr, </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(err, res){
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }
    })
}

findByIdAndUpdate();</span></pre>
</div>
<p>  </p>
<p>  其它更新方法</p>
<p>  <em><span style="color: rgba(0, 204, 255, 1)">Model.findOneAndUpdate(, , , )</span></em>      //找到一条记录并更新</p>
<p>  </p>
<p>  <strong>删除</strong></p>
<p>  <em><span style="color: rgba(0, 204, 255, 1)">Model.remove(conditions, )</span></em></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> del(){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> wherestr = {'username' : 'Tracy McGrady'<span style="color: rgba(0, 0, 0, 1)">};
   
    User.<span style="color: rgba(255, 0, 0, 1)">remove</span>(wherestr, </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(err, res){
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }
    })
}

del();</span></pre>
</div>
<p>  结果就不贴了,res中会返回是否成功以及影响的行数:<em>{"ok":1,"n":1}</em></p>
<p>&nbsp;</p>
<p>  其它常用方法还有:&nbsp;</p>
<p>  <em><span style="color: rgba(0, 204, 255, 1)">Model.findByIdAndRemove(id, , )      </span></em></p>
<p><span style="color: rgba(0, 204, 255, 1)"><em>  Model.findOneAndRemove(conditions, , )</em></span></p>
<p>&nbsp;</p>
<p>  <strong>条件查询</strong></p>
<p>  已先插入一些测试数据&nbsp;。。</p>
<p><span style="color: rgba(0, 204, 255, 1)"><em>  Model.find(conditions, , , )</em></span></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> getByConditions(){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> wherestr = {'username' : 'Tracy McGrady'<span style="color: rgba(0, 0, 0, 1)">};
   
    User.<span style="color: rgba(255, 0, 0, 1)">find</span>(wherestr, </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(err, res){
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }
    })
}

getByConditions();</span></pre>
</div>
<p>  结果我就不展示了</p>
<p>  第2个参数可以设置要查询输出的字段,比如改成</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> getByConditions(){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> wherestr = {'username' : 'Tracy McGrady'<span style="color: rgba(0, 0, 0, 1)">};
    </span><span style="color: rgba(255, 0, 0, 1)">var opt = {"username": 1 ,"_id": 0</span><span style="color: rgba(0, 0, 0, 1)"><span style="color: rgba(255, 0, 0, 1)">};</span>
   
    User.find(wherestr, opt, </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(err, res){
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }
    })
}

getByConditions();</span></pre>
</div>
<p>  输出只会有username字段,设置方法如上,1表示查询输出该字段,0表示不输出</p>
<p>&nbsp;</p>
<p>  比如我要查询年龄范围条件应该怎么写呢?</p>
<p><span style="color: rgba(0, 204, 255, 1)"><em>  User.find({userage: {$gte: 21, $lte: 65}}, callback); &nbsp; &nbsp;</em></span><span style="color: rgba(0, 204, 255, 1)"><span style="color: rgba(0, 0, 0, 1)">//这表示查询年龄大于等21而且小于等于65岁</span></span></p>
<p>&nbsp;</p>
<p><span style="color: rgba(0, 204, 255, 1)"><span style="color: rgba(0, 0, 0, 1)">  其实类似的还有:</span></span><span style="color: rgba(0, 204, 255, 1)"><span style="color: rgba(0, 0, 0, 1)"> </span></span></p>
<p>  $or    或关系</p>
<p>  $nor    或关系取反</p>
<p>  $gt    大于</p>
<p>  $gte    大于等于</p>
<p>  $lt     小于</p>
<p>  $lte    &nbsp;小于等于</p>
<p>  $ne &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;不等于</p>
<p>  $in &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 在多个值范围内</p>
<p>  $nin &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 不在多个值范围内</p>
<p>  $all &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;匹配数组中多个值</p>
<p>  $regex  正则,用于模糊查询</p>
<p>  $size   匹配数组大小</p>
<p>  $maxDistance  范围查询,距离(基于LBS)</p>
<p>  $mod   &nbsp; 取模运算</p>
<p>  $near   邻域查询,查询附近的位置(基于LBS)</p>
<p>  $exists   &nbsp;字段是否存在</p>
<p>  $elemMatch  匹配内数组内的元素</p>
<p>  $within  范围查询(基于LBS)</p>
<p>  $box    范围查询,矩形范围(基于LBS)</p>
<p>  $center &nbsp; &nbsp; &nbsp; 范围醒询,圆形范围(基于LBS)</p>
<p>  $centerSphere  范围查询,球形范围(基于LBS)</p>
<p>  $slice    查询字段集合中的元素(比如从第几个之后,第N到第M个元素)</p>
<p>  </p>
<p>  可能还有一些,没什么印象,大家自行看看api ^_^!  </p>
<p>&nbsp;</p>
<p>  <strong>数量查询</strong></p>
<p><em><span style="color: rgba(0, 204, 255, 1)">  Model.count(conditions, )</span></em></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> getCountByConditions(){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> wherestr =<span style="color: rgba(0, 0, 0, 1)"> {};
   
    User.<span style="color: rgba(255, 0, 0, 1)">count</span>(wherestr, </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(err, res){
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }
    })
}</span></pre>
<pre><span>getCountByConditions();</span></pre>
</div>
<p>  res会输出数量,也可以传入条件做条件查询!</p>
<p>  <strong>根据_id查询</strong></p>
<p><em><span style="color: rgba(0, 204, 255, 1)">  Model.findById(id, , , )</span></em></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> getById(){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> id = '56f261fb448779caa359cb73'<span style="color: rgba(0, 0, 0, 1)">;
   
    User.<span style="color: rgba(255, 0, 0, 1)">findById</span>(id, </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(err, res){
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }
    })
}

getById();</span></pre>
</div>
<p>  这个还是比较常用,要据ID得到数据!  </p>
<p>  <strong>模糊查询</strong></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> getByRegex(){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> whereStr = {'username':{<span style="color: rgba(255, 0, 0, 1)">$regex</span>:/m/<span style="color: rgba(0, 0, 0, 1)">i}};
   
    User.find(whereStr, </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(err, res){
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }
    })
}

getByRegex();</span></pre>
</div>
<p>  上面示例中查询出所有用户名中有'm'的名字,且不区分大小写,模糊查询比较常用,正则形式匹配,正则方式就是javascript正则,用到的比较多!</p>
<p>  <strong>分页查询</strong></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">var</span> User = require("./user.js"<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> getByPager(){
   
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> pageSize = 5;                   <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">一页多少条</span>
    <span style="color: rgba(0, 0, 255, 1)">var</span> currentPage = 1;                <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">当前第几页</span>
    <span style="color: rgba(0, 0, 255, 1)">var</span> sort = {'logindate':-1};      <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">排序(按登录时间倒序)</span>
    <span style="color: rgba(0, 0, 255, 1)">var</span> condition = {};               <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">条件</span>
    <span style="color: rgba(0, 0, 255, 1)">var</span> skipnum = (currentPage - 1) * pageSize;   <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">跳过数</span>
<span style="color: rgba(0, 0, 0, 1)">   
    User.find(condition).skip(skipnum).limit(pageSize).sort(sort).exec(</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> (err, res) {
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
            console.log(</span>"Error:" +<span style="color: rgba(0, 0, 0, 1)"> err);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(</span>"Res:" +<span style="color: rgba(0, 0, 0, 1)"> res);
      }
    })
}

getByPager();</span></pre>
</div>
<p>  分页是用得比较多的查询,分页原理用过其它数据库的都知道,分页用到的函数和mysql的比较类似</p>
<p>  上面我用到<span style="color: rgba(255, 0, 0, 1)">sort(),<span style="color: rgba(0, 0, 0, 1)">这个是排序规则,就不单讲了!</span></span></p>
<h1 id="node_others" class="wilson_h1">其它操作</h1>
<p>  其它还有比较多常用的</p>
<p>  <strong>索引和默认值</strong></p>
<p>  再看看我对user.js这个schema的修改</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 用户信息
</span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">var</span> mongoose = require('./db.js'<span style="color: rgba(0, 0, 0, 1)">),
    Schema </span>=<span style="color: rgba(0, 0, 0, 1)"> mongoose.Schema;

</span><span style="color: rgba(0, 0, 255, 1)">var</span> UserSchema = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Schema({         
    username : { type: String , <span style="color: rgba(255, 0, 0, 1)">index: </span></span><span style="color: rgba(255, 0, 0, 1)">true</span>},                  <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户账号</span>
    userpwd: {type: String},                        <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    userage: {type: Number},                        <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">年龄</span>
    logindate : { type: Date, <span style="color: rgba(255, 0, 0, 1)">default:Date.now</span>}                     <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">最近登录时间</span>
<span style="color: rgba(0, 0, 0, 1)">});

module.exports </span>= mongoose.model('User',UserSchema);</pre>
</div>
<p>  index :建索引</p>
<p>  default:默认值</p>
<p>  </p>
<p>  <strong>LBS地址位置</strong></p>
<div class="cnblogs_code">
<pre>lbs : { type: Array, index: '2d', sparse: <span style="color: rgba(0, 0, 255, 1)">true</span> }   <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">地理位置</span></pre>
</div>
<p>  上面有介绍过很多基于LBS的条件查询,Schema中定义时如上</p>
<p>  LBS查询对于一些基于LBS应用会用得比较多。</p>
<p>&nbsp;</p>
<p>  <strong>其它常用方法</strong></p>
<p><span style="color: rgba(0, 204, 255, 1)"><em>  Model.distinct(field, , ) </em></span>                 //去重</p>
<p><span style="color: rgba(0, 204, 255, 1)"><em>  Model.findOne(conditions, , , ) </em></span>            //查找一条记录</p>
<p><em><span style="color: rgba(0, 204, 255, 1)">  Model.findOneAndRemove(conditions, , ) </span></em>          //查找一条记录并删除</p>
<p><em><span style="color: rgba(0, 204, 255, 1)">  Model.findOneAndUpdate(, , , )</span>  </em>    //查找一条记录并更新</p>
<p>&nbsp;</p>
<h1 id="node_aferwords" class="wilson_h1">写在之后...</h1>
<p>  mongoose操作基本入门大致就是这些,自已试一下,入门完全没问题,并且比node-mongodb-native还是要简单明了一些,</p>
<p>  在node.js中操作数据库,如果逻辑相对复杂时,大量的回调嵌套还是比较郁闷的,下一篇于mongoose操作多逻辑组合回调嵌套的问题给出一种方案^_^!</p>
<p>&nbsp;</p>
</div>

</div>
<div id="MySignature" role="contentinfo">
    <div style="color:#399AB2;">
<p style="line-height: 20px; background: #CCC no-repeat 2% 50%; font-size: 12px; border: #e0e0e0 1px dashed; padding: 10px;color:#399AB2;">
作 &nbsp; 者:&nbsp;&nbsp;
Porschev[钟慰]
<br/>
出 &nbsp; 处:&nbsp;&nbsp;
http://www.cnblogs.com/zhongweiv/
<br/>
微 &nbsp; 博: &nbsp;&nbsp;&nbsp;
http://weibo.com/porschev
<br/>
欢迎任何形式的转载,但请务必注明原文详细链接
</p>
</div><br><br>
来源:https://www.cnblogs.com/zhongweiv/p/mongoose.html
頁: [1]
查看完整版本: Nodejs学习笔记(十四)— Mongoose介绍和入门