11. mongoose学习笔记
创建时间:2023-02-19 12:43
长度:948
浏览:51
评论:0
mongoose是什么?
是node中介供操作mongoDB的模块
mongoose能干嘛?
通过node语法实现mongoDB数据库的增删改查,从而实现用node写程序来管理mongoDB数据库
如何安装?
npm i mongoose
OR
yarn add mongoose
中文网: http://www.mongoosejs.net/
Schema
作用:用来约束MongoDB文档数据,哪些字段必须,哪些字段可选...
Model
作用:一个模型对应一个集合,通过模型来管理集合中的数据
findOneAndUpdate
查找到一个并且更新
xxxScaema.findOneAndUpdate({ }, { }, {}, callback);
例1: 查找到用户ID666更新用户名为huangcy.com
xxxScaema.findOneAndUpdate(
{ userId: 666 },
{
$set: { username: "huangcy.com }
}, {}, err => {
if (err) {
console.log('更新失败');
return;
}
console.log('更新成功');
}
);
例2: 查找到用户ID666更新用户金额+200
ps: 当字段(key)不存在时,使用upsert: true来增加key
xxxScaema.findOneAndUpdate(
{ userId: 666 },
{
$set: { username: "huangcy.com },
upsert: true # 当例
}, {}, err => {
if (err) {
console.log('更新失败');
return;
}
console.log('更新成功');
}
);