1.1【update()】
Model.update(conditions, doc, [options], [callback])
- 参数
conditions
:查询条件
doc
:需要修改的数据(插入的数据)
[options]
:控制选项
safe (boolean): 默认为true。安全模式。 upsert (boolean): 默认为false。如果不存在则创建新记录。 multi (boolean): 默认为false。是否更新多个查询记录。 runValidators: 如果值为true,执行Validation验证。 setDefaultsOnInsert: 如果upsert选项为true,在新建时插入文档定义的默认值。 strict (boolean): 以strict模式进行更新。 overwrite (boolean): 默认为false。禁用update-only模式,允许覆盖记录。
[callback]
:回调函数
若设置了查询条件,当数据库不满足时默认什么也不发生;
update()
方法中的回调函数不能省略,否则数据不会更新,当回调无有用信息时可以使用exec()
简化stuModel.update({name:'小明'},{$set:{test:34}}.exec())
案例
//第一步,引入mongoose
const mongoose = require('mongoose')
//第二步,连接数据库
mongoose.connect('mongodb://localhost:27017/student',err=>{
if(!err){
//第三步,创建模板
var Schema =new mongoose.Schema({ name:String,grades:Number,test:{type:Number,default:0}})
// var Schema = new Schema()
//第四步,将模板映射到集合并创建
var stuModel = mongoose.model('grades',Schema)
//查询name为小明的数据,并将其test更改为34
//若有多个文档,默认只更新第一个
stuModel.update({name:'小明'},{$set:{test:34}},(err,raw)=>{
console.log(raw)
})
//{ n: 1, nModified: 1, ok: 1 }
//6017befb5c36d64d08b72576 小明 68 0 34
}
})
1.2【updateOne()】
Model.updateOne(conditions, doc, [options], [callback])
与
update()
相似,唯一区别为updateOne()
默认更新一个文档,即使设置{multi:true}
也无法只更新一个文档
1.3【updateMany()】
Model.updateMany(conditions, doc, [options], [callback])
- 与
update()
相似,唯一区别为updateMany()
默认更新多个文档,即使设置{multi:false}
也无法只更新一个文档
1.4【find()+save()】
用于复杂更新
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',err=>{
if(!err){
var Schema =new mongoose.Schema({ name:String,grades:Number,test:{type:Number,default:0}})
var stuModel = mongoose.model('grades',Schema)
//查询成绩小于60的数据,并在其名字后添加‘:差生’字段
stuModel.find({grades:{$lt:60}},(err,docs)=>{
console.log(docs);
/*[{test: 0,_id: 6017c455ba09d355a49ec8eb,name: '小红',grades: 52,__v: 0},
{test: 0,_id: 6017c455ba09d355a49ec8ec,name: '小刚',grades: 46,__v: 0}]*/
docs.forEach((item,index,arr) => {
item.name += ':差生'
//将修改后的数据保存
item.save()
})
console.log(docs)
/*[{test: 0,_id: 6017c455ba09d355a49ec8eb,name: '小红:差生',grades: 52,__v: 0},
{test: 0,_id: 6017c455ba09d355a49ec8ec,name: '小刚:差生',grades: 46,__v: 0}]*/
})
}
})
1.5【findOne() + save()】
用于复杂更新
findOne()
返回值为文档对象const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',err=>{
if(!err){
var Schema =new mongoose.Schema({ name:String,grades:Number,test:{type:Number,default:0}})
var stuModel = mongoose.model('grades',Schema)
//查询成绩小于60的数据,并在其名字后添加‘:差生’字段
stuModel.findOne({name:'小明'},(err,doc)=>{
console.log(doc);
//[{test: 34,_id: 6017c455ba09d355a49ec8eb,name: '小明',grades: 68,__v: 0},
doc.age += 10
doc.save()
console.log(docs)
//[{test: 34,_id: 6017c455ba09d355a49ec8eb,name: '小明',grades: 78,__v: 0}
})
}
})
1.6【fingOneAndUpdate()】
Model.findOneAndUpdate([conditions], [update], [options], [callback])
1.7【findByIdAndUpdate()】
Model.findByIdAndUpdate([conditions], [update], [options], [callback])