Model.update(conditions, update, [options], [callback])
db.js
var mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/whhhh', { useMongoClient: true }); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function (callback) { console.log("数据库成功连接"); }); module.exports = db;
user.js
var mongoose = require('mongoose'); var db = require("./db.js"); var Schema=mongoose.Schema; var UserSchema = new mongoose.Schema({ username:{type:String}, usersex:{type:String}, userage:{type:Number} }); module.exports = mongoose.model('User',UserSchema);
try.js
var User = require("./user.js"); function update(){ var wherestr = {'username' : 'zhangming'}; var updatestr = {'userage': '20'}; User.update(wherestr, updatestr, function(err, res){ if (err) { console.log("Error:" + err); } else { console.log("Res:" + res); } }) } update();
更新前:
更新后:
findByIdAndUpdate,这种比较有指定性,就是根据_id
Model.findByIdAndUpdate(id, [update], [options], [callback])
try.js
var User = require("./user.js"); function findByIdAndUpdate() { var id='59fa714f16ee5b557824b8e5'; var updatestr={'usersex':'nu'}; User.findByIdAndUpdate (id,updatestr,function(err,res) { if (err) { console.log("Error:" + err); } else { console.log("Res:" + res); } } ) } findByIdAndUpdate();
效果:
在webstorm:
在robmongo工具中查看
2017-11-02 09:24:06