假設(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)行
});
Documents
Mongoose文檔表示對存儲在MongoDB中的文檔的一對一映射。每個文檔都是其模型的實例挡逼。
Updating
有多種方式可以更新文檔玖喘。我們首先來看一個使用findById的傳統(tǒng)方法:
let Schema = mongoose.Schema;
let schema = new Schema({
name:String
});
let Person = mongoose.model('Person',schema);
Person.findById("5879c65893963d18fe77a31b",function(err,man){
if(err){
return console.error(err);
}
man.name = 'Blu';
man.save(function(err){
if(err){
return console.error(err);
}
console.log('保存成功');
});
});
這種方法包括首先從Mongo中檢索文檔咙轩,然后發(fā)出更新命令(通過調(diào)用save觸發(fā))券躁。但是艰毒,如果我們不需要在我們的應(yīng)用程序中返回的文檔,并且只想直接更新數(shù)據(jù)庫中的屬性占婉,那么Model#update適合我們:
let Schema = mongoose.Schema;
let schema = new Schema({
name:String
});
let Person = mongoose.model('Person',schema);
Person.update({_id:"5879c65893963d18fe77a31b"},{$set:{name:'SHE'}},function(){
//這里不返回文檔
});
如果我們確實需要在我們的應(yīng)用程序中返回文檔泡嘴,有另一個更好的選擇:
let Schema = mongoose.Schema;
let schema = new Schema({
name:String
});
let Person = mongoose.model('Person',schema);
Person.findByIdAndUpdate('5879c65893963d18fe77a31b',{$set:{name:"李尋歡"}},function(err,man){
if(err){
return console.error(err);
}
console.log(man);
});
Sub Docs
子文檔是具有自己的模式的文檔,它們是父文檔數(shù)組的元素:
let childSchema = new Schema({ name: 'string' });
let parentSchema = new Schema({ children: [childSchema]});
子文檔享有與普通文檔相同的功能逆济。唯一的區(qū)別是它們不單獨(dú)保存酌予,它們在保存頂級父文檔時保存。
let Schema= mongoose.Schema;
let childrenSchema = new Schema({
name:String
});
let parentSchema = new Schema({
children:[childrenSchema]
});
let Parent = mongoose.model('Parent',parentSchema);
let parent = new Parent({
children:[{
name:'Matt'
},{
name:'Sarah'
}]
});
parent.save(function(err,parent){
if(err){
return console.error(err);
}
console.log(parent);
});
如果在子文檔中間件中發(fā)生錯誤奖慌,它會冒泡到父對象的save()回調(diào)抛虫,因此錯誤處理是一個快速!
let Schema= mongoose.Schema;
let childrenSchema = new Schema({
name:String
});
childrenSchema.pre('save',function(next){
if('noshower' == this.name){
return next(new Error(this.name+'禁止取'));
}
next();
});
let parentSchema = new Schema({
children:[childrenSchema]
});
let Parent = mongoose.model('Parent',parentSchema);
let parent = new Parent({
children:[{
name:'noshwoer'
},{
name:'noshower'
}]
});
parent.save(function(err,parent){
if(err){
return console.error(err); //Error: noshower禁止取
}
console.log(parent);
});
Finding a sub-document
每個文檔都有一個_id简僧。 DocumentArrays有一個特殊的id方法建椰,通過其_id查找文檔。
let Schema= mongoose.Schema;
let childrenSchema = new Schema({
name:String
});
childrenSchema.pre('save',function(next){
if('noshower' == this.name){
return next(new Error(this.name+'禁止取'));
}
next();
});
let parentSchema = new Schema({
children:[childrenSchema]
});
let Parent = mongoose.model('Parent',parentSchema);
//先找到父文檔 Parent.findOne({_id:'5879d25dc3352e1ad7855f65'},function(err,parent){
if(err){
return console.error(err);
}
//查詢子文檔
let doc =parent.children.id('5879d25dc3352e1ad7855f67');
console.log(doc.name); //Matt
});
Adding sub-docs
MongooseArray方法(例如push岛马,unshift棉姐,addToSet和其他方法)將參數(shù)強(qiáng)制轉(zhuǎn)換為其正確類型:
// 一次性存五個名字
let Schema= mongoose.Schema;
let childrenSchema = new Schema({
name:String
});
childrenSchema.pre('save',function(next){
if('noshower' == this.name){
return next(new Error(this.name+'禁止取'));
}
next();
});
let parentSchema = new Schema({
children:[childrenSchema]
});
let Parent = mongoose.model('Parent',parentSchema);
let parent = new Parent();
let names = ['John','Michelle','Amy','Kim','Mary'];
for(let val of names){
parent.children.push({name:val});
}
parent.save(function(err,parent){
if(err){
return console.error(err);
}
console.log('success'); //success
});
Removing docs
每個子文檔都有自己的remove方法。
let Schema= mongoose.Schema;
let childrenSchema = new Schema({
name:String
});
childrenSchema.pre('save',function(next){
if('noshower' == this.name){
return next(new Error(this.name+'禁止取'));
}
next();
});
let parentSchema = new Schema({
children:[childrenSchema]
});
let Parent = mongoose.model('Parent',parentSchema);
Parent.findOne({'_id':"5879d25dc3352e1ad7855f65"},function(err,parent){
parent.children.id('5879d25dc3352e1ad7855f67').remove();
parent.save(function(err){
if(err){
return console.error(err);
}
console.log('刪除成功');
})
});
如果你不需要訪問子文檔模式實例啦逆,那么你也可以通過傳遞一個對象來聲明sub-docs
let parentSchema = new Schema({
children: [{ name: 'string' }]
})