使用mongoose更新mongodb的问题

浏览:61日期:2023-06-19

问题描述

知道mongodb可以通过设置update的第三个参数为true来实现没有数据时插入,有数据时更新。那使用mongoose封装的update方法如何传入这个参数呢?mongoose的文档中提供的是update(doc, options, callback)这三个参数

问题解答

回答1:

http://mongoosejs.com/docs/ap...

使用mongoose更新mongodb的问题

MyModel.update({ name: ’Tobi’ }, { ferret: true }, { upsert: true }, function (err, raw) { if (err) return handleError(err); console.log(’The raw response from Mongo was ’, raw);});

回答2:

将update方法第3个参数的upsert属性设为true即可

Book.update(// 查询{ name: 'The Kite Runner'},// 更新{ auther: 'Khaled Hosseini'},// 其他参数{ upsert: true,}, function(err, doc){ if (err) console.log(err); console.log(doc);});

当数据库中存在The Kite Runner时,更新文档的auther属性;

当数据库中没有The Kite Runner时,插入The Kite Runner文档;

相关文章: