假設(shè)以下代碼都運(yùn)行在
let mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
let db = mongoose.connection;
db.on('error', () => {
console.error('鏈接失敗');
});
db.once('open', function () {
//下面講到的所有代碼都在這里運(yùn)行
});
increment
增加文檔版本號(hào)
//一開(kāi)始的版本號(hào)_v是0
let query = Person.findOne({ name: 'noshower' }, function (err, person) {
person.increment();
person.save(function (err, parent) {
if (err) {
return console.error(err);
}
//現(xiàn)在_v是1
});
});
remove
從db中刪除此文檔胳赌。
Person.findOne({name:'noshower'},function(err,result){
if(err){
return console.error(result);
}
console.log(result);//{ _id: 587a02251d73bb1ec61ace04, name: 'noshower',age: 22,occupation: 'teacher',__v: 1 }
result.remove(function(err,result){
if(err){
return console.error(err);
}
Person.findById(result._id,function(err,result){
if(err){
return console.error(err);
}
console.log(result); //null 被刪了
})
});
});
model(name)
返回另一個(gè)Model實(shí)例
let Schema = mongoose.Schema;
let schema = new Schema({
name: String,
age: Number,
occupation: String
});
let Person = mongoose.model('Person', schema);
let Woman = mongoose.model('Woman', schema);
Woman.model('Person').findById('587a0234a693c31ed46c4885',function(err,result){
if(err){
return console.error(err);
}
console.log(result);
});
save([fn])
保存此文檔
let Schema = mongoose.Schema;
let schema = new Schema({
name: String,
age: Number,
occupation: String
});
let Person = mongoose.model('Person', schema);
let person = new Person({
name:'馬克',
age:24,
occupation:'programmer'
});
person.save(function(err,product,numberAffected){
if(err){
return console.error(err);
}
console.log(numberAffected); //1
});
回調(diào)將接收三個(gè)參數(shù)帖世,err如果發(fā)生錯(cuò)誤乎折,product是保存的product缤底,numberAffected扁耐,當(dāng)文檔在數(shù)據(jù)庫(kù)中找到和更新時(shí),為1款熬,否則為0深寥。
fn callback是可選的。如果沒(méi)有傳遞fn并且驗(yàn)證失敗贤牛,那么將在用于創(chuàng)建此模型的連接上發(fā)出驗(yàn)證錯(cuò)誤惋鹅。
let db = mongoose.createConnection(..);
let schema = new Schema(..);
let Product = db.model('Product', schema);
db.on('error', handleError);
然而,如果你想要更多的本地錯(cuò)誤處理殉簸,你可以添加一個(gè)error監(jiān)聽(tīng)器到模型闰集,并處理錯(cuò)誤沽讹。
Product.on('error', handleError);
count
計(jì)算數(shù)據(jù)庫(kù)集合中匹配的文檔數(shù)。
let Schema = mongoose.Schema;
let schema = new Schema({
name: String,
age: Number,
occupation: String
});
let Person = mongoose.model('Person', schema);
Person.count({name:'noshower'},function(err,count){
if(err){
return console.error(err);
}
console.log(count);//2 說(shuō)明數(shù)據(jù)庫(kù)中返十,叫“noshower”的person有兩個(gè)
});
create
用于創(chuàng)建新文檔的快捷方式妥泉,如果有效,將自動(dòng)保存到數(shù)據(jù)庫(kù)洞坑。
Person.create({name:'Ali'},{name:'PengHu'},function(err,person1,person2){
if(err){
return console.error(err);
}
// 生成了兩個(gè)文檔
console.log(person1);//{ __v: 0, name: 'Ali', _id: 587a3c2e09a15c236e3fca37 }
console.log(person2);// { __v: 0, name: 'PengHu', _id: 587a3c2e09a15c236e3fca38 }
});
//傳遞一個(gè)數(shù)組
let array = [{
name:'高虎'
},{
name:'林俊杰'
}];
//此時(shí)回調(diào)函數(shù)接受到只有兩個(gè)參數(shù)盲链,一個(gè)是err,另一個(gè)person1。person2是undefined
Person.create(array,function(err,person1,person2){
if(err){
return console.error(err);
}
console.log(person1);//[ { __v: 0, name: '高虎', _id: 587a3d3cdf8cc623a034de09 },{ __v: 0, name: '林俊杰', _id: 587a3d3cdf8cc623a034de0a } ]
console.log(person2); // undefined
});
distinct
為不同操作創(chuàng)建查詢(xún)
let Schema = mongoose.Schema;
let schema = new Schema({
name: String,
age: Number,
occupation: String
});
let Person = mongoose.model('Person',schema);
//找到數(shù)據(jù)庫(kù)所有age=22的文檔迟杂,并將name字段值以數(shù)組形式返回
Person.distinct('name',{age:22},function(err,result){
if(err){
return console.error(err);
}
console.log(result);//[ '李尋歡', '愛(ài)因斯坦', 'noshower' ]
});
let query = Person.distinct('url');
query.exec(function(){
console.log('ok')
});
find
查找文檔
Model.find(conditions,fields,options,callback);
在發(fā)送命令之前刽沾,conditions將轉(zhuǎn)換為它們各自的SchemaTypes。
//查找年齡至少24
Person.find({age:{$gte:24}},function(err,result){
if(err){
return console.error(err);
}
console.log(result);
});
//查找年齡至少24排拷,僅選擇name字段侧漓。
Person.find({age:{$gte:24}},'name',function(err,result){
if(err){
return console.error(err);
}
console.log(result);
});
// 查找年齡至少24,僅選擇name字段,且跳過(guò)兩個(gè)
Person.find({age:{$gte:22}},"name",{skip:2},function(err,result){
if(err){
return console.error(err);
}
console.log(result);
});
findById
按id查找單個(gè)文檔监氢。
Model.findById(id,fields,options,callback);
//選擇name字段
Person.findById('587a3aae75b3c5758ca6877d',"name",function(err,person){
if(err){
return console.error(err);
}
console.log(person);
});
findByIdAndRemove
Model.findByIdAndRemove(id,[options],[callback])
查找匹配的文檔布蔗,將其刪除,將找到的文檔(如果有)傳遞到回調(diào)浪腐。 如果傳遞了callback纵揍,則立即執(zhí)行,否則返回Query對(duì)象议街。
//
A.findByIdAndRemove(id, options, callback) // 立即執(zhí)行
executesA.findByIdAndRemove(id, options) // 返回query
QueryA.findByIdAndRemove(id, callback) // 立即執(zhí)行
executesA.findByIdAndRemove(id) // 返回 query
QueryA.findByIdAndRemove() //返回query
findByIdAndUpdate
Model.findByIdAndUpdate(id, [update], [options], [callback])
找到匹配的文檔泽谨,根據(jù)update變量更新它,傳遞任何選項(xiàng)特漩,并將找到的文檔(如果有)返回到回調(diào)吧雹。如果回調(diào)被傳遞,則查詢(xún)立即執(zhí)行涂身,否則返回一個(gè)Query對(duì)象雄卷。
Options:
- new : true 返回修改的文檔而不是原始文檔。默認(rèn)為true
//將new設(shè)置為false,將返回原始文檔
Person.findByIdAndUpdate('587a3aae75b3c5758ca6877d',{name:'光環(huán)'},{new:false},function(err,person){
if(err){
return console.error(err);
}
console.log(person);
});
-
upsert:false 如果對(duì)象不存在蛤售,則創(chuàng)建對(duì)象龙亲。默認(rèn)為false
//查找的id并不存在,將upsert設(shè)置為true,此時(shí)將創(chuàng)建對(duì)象 Person.findByIdAndUpdate('587a3aae75b3c5758ca687dd',{name:'光環(huán)'},{upsert:true},function(err,person){ if(err){ return console.error(err); } });
sort 如果按照條件找到多個(gè)文檔悍抑,請(qǐng)?jiān)O(shè)置排序順序以選擇要更新的文檔
select 設(shè)置要返回的文檔字段
Model.findOne
查找一個(gè)文檔
Model.findOne(conditions, [fields], [options], [callback])
在發(fā)送命令之前,conditions將轉(zhuǎn)換為它們各自的SchemaTypes杜耙。
//查找name是noshower的文檔搜骡,返回name字段
Person.findOne({name:'noshower'},'name',function(err,person){
if(err){
return console.error(err);
}
console.log(person);
});
findOneAndRemove
Model.findOneAndRemove(conditions, [options], [callback])
查找匹配的一個(gè)文檔,將其刪除佑女,將找到的文檔(如果有)傳遞到callback记靡。 如果回調(diào)函數(shù)被傳遞谈竿,則立即執(zhí)行;否則返回一個(gè)Query對(duì)象。
findOneAndUpdate
Model.findOneAndUpdate([conditions], [update], [options], [callback])
remove
Model.remove(conditions, [callback])
從集合中刪除文檔摸吠。
// 刪除所有name=“光環(huán)”的文檔
Person.remove({name:'光環(huán)'},function(err){
if(err){
return console.error(err);
}
});
//remove如果在document上調(diào)用空凸,表示刪除這條文檔。z在model上調(diào)用寸痢,表示刪除所有匹配的文檔呀洲。
person.remove(function(err,person){
})
要?jiǎng)h除文檔而不等待MongoDB的響應(yīng),不要傳遞回調(diào)啼止,然后在返回的Query上調(diào)用exec:
let query = Person.remove({ _id: id });
query.exec();
此方法直接向MongoDB發(fā)送一個(gè)remove命令道逗,不涉及Mongoose文檔。因?yàn)椴簧婕癕ongoose文檔献烦,所以不執(zhí)行中間件(hook)滓窍。
update
Model.update(conditions, update, [options], [callback]
更新數(shù)據(jù)庫(kù)中的文檔而不返回它們。
//更新所有年齡在18歲以上的文檔巩那,職業(yè)更新為cleaner
Person.update({age:{$gte:18}},{occupation:'cleaner'},{multi:true},function(err,numberAffected,raw){
if(err){
return console.error(err);
}
console.log(numberAffected);
console.log(raw);
});
Valid options:
- safe (boolean)安全模式(默認(rèn)為在schema中設(shè)置的值(true))
- upsert (boolean) 是否創(chuàng)建文檔如果它不匹配(false)
- multi (boolean) 是否應(yīng)更新多個(gè)文檔(false)
- strict (boolean) 覆蓋此更新的strict選項(xiàng)
- overwrite (boolean) 禁用僅更新模式吏夯,允許您覆蓋doc(false)
回調(diào)函數(shù)接收(err,numberAffected即横,rawResponse)
- err 是錯(cuò)誤如果錯(cuò)誤發(fā)生
- numberAffected是Mongo報(bào)告的更新文檔的數(shù)量
- rawResponse是Mongo的完整響應(yīng)
where
創(chuàng)建查詢(xún)噪生,應(yīng)用已通過(guò)的條件,并返回查詢(xún)令境。
Model.where(path, [val])
User.find({age: {$gte: 21, $lte: 65}}, callback);
//也可以這樣
User.where('age').gte(21).lte(65).exec(callback);