mongoose 常用數據庫操作 查詢
阿新 • • 發佈:2017-11-02
.cn var alt storm user style color pan logs
條件查詢
Model.find(conditions, [fields], [options], [callback])
demo1
try.js
var User = require("./user.js"); function getByConditions(){ var wherestr = {‘username‘ : ‘xiaoming‘}; User.find(wherestr, function(err, res){ if (err) { console.log("Error:" + err); }else { console.log("Res:" + res); } }) } getByConditions();
在robo查看數據庫:
在webstorm 中查看輸出結果:
demo2
try.js
var User = require("./user.js"); function getByConditions(){ var wherestr = {‘username‘ : ‘xiaoming‘}; var opt = {"username": 1 ,"_id": 0}; User.find(wherestr,opt, function(err, res){if (err) { console.log("Error:" + err); } else { console.log("Res:" + res); } }) } getByConditions();
輸出結果:
年齡查詢
在robo查看數據庫:
try.js
var User = require("./user.js"); function getByConditions(){ User.find({userage: {$gte: 13, $lte: 30}}, function(err, res){if (err) { console.log("Error:" + err); } else { console.log("Res:" + res); } }) } getByConditions();
$gte: 13, $lte: 30:表示大於等於13而且小於等於30歲
在webstorm中輸出結果:
數量查詢
Model.count(conditions, [callback])
try.js
var User = require("./user.js"); function getCountByConditions(){ var wherestr={}; User.count(wherestr, function(err, res){ if (err) { console.log("Error:" + err); } else { console.log("Res:" + res); } }) } getCountByConditions();
在webstorm中輸出結果:
根據_id查詢
Model.findById(id, [fields], [options], [callback])
在robo中查看 id=59fa8b401061f8333095975a 的語句
try.js
var User = require("./user.js"); function getById(){ var id=‘59fa8b401061f8333095975a‘; User.findById(id, function(err, res){ if (err) { console.log("Error:" + err); } else { console.log("Res:" + res); } }) } getById();
輸出結果:
模糊查詢
try.js
var User = require("./user.js"); function getByRegex(){ var whereStr={‘username‘:{$regex:/z/i}}; User.find(whereStr, function(err, res){ if (err) { console.log("Error:" + err); } else { console.log("Res:" + res); } }) } getByRegex();
上面示例中查詢出所有用戶名中有‘z‘的名字,不區分大小寫
輸出結果:
2017-11-02 11:41:51
mongoose 常用數據庫操作 查詢