本文是紧接着 Mongoose 的增加与查询的下集,所以在这里废话不多说直接上内容。
修改
根据条件更改:
- 第一个参数:需要更新的条件
- 第二个参数:更新的内容
- 第三个参数:更新的结果返回值
User.update({name: 'ls'}, {$set: {age: 888}}, (err, docs) => {
if (!err) {
console.log('更新成功');
console.log(docs);
}
});
根据条件修改(带额外配置):
- 第一个参数:需要更新的条件
- 第二个参数:更新的内容
- 第三个参数:更新的额外配置
- 第四个参数:更新的结果
User.update({name: 'ls'}, {$set: {age: 888}}, {multi: true}, (err, docs) => {
if (!err) {
console.log('更新成功');
console.log(docs);
}
});
根据条件修改(Promise):
(async () => {
let result = await User.update({name: 'ls'}, {$set: {age: 123}}, {multi: true});
console.log(result);
})();
删除
根据条件删除:
User.remove({name: 'ww'}, {}, (err, docs) => {
if (!err) {
console.log('删除成功');
console.log(docs);
}
});
根据条件删除(只删除满足条件的一条):
User.deleteOne({name: 'BNTang'}, (err, docs) => {
if (!err) {
console.log('删除成功');
console.log(docs);
}
});
根据条件删除(只删除满足条件的一条,Promise):
(async () => {
let result = await User.deleteOne({name: 'BNTang'});
console.log(result);
})();