【MongoDB】【mongoose】基础使用

    科技2022-07-15  108

    文档

    http://www.mongoosejs.net/docs/index.html

    安装 配置

    以下为ts写法

    //安装 npm i mongoose //引入 import mongoose from 'mongoose'; //连接数据库 mongoose .connect('mongodb://test:123456@localhost:27017/todolist', { useFindAndModify: false }) .then(() => { console.log('数据库连接成功'); }) .catch((err) => { console.log('数据库连接失败:', err); });

    数据库操作

    基础概念

    Schema,Model,Document

    Schema 实例 会映射到 数据库的一个Collection,并定义它的组成

    Model 由Schema创建实例。实例可以操作数据库

    Document 由Model创建实例。映射 collection的文档。也可以操作数据库

    基础使用

    import mongoose from 'mongoose'; export type ItemInterface = { _id: number; user_id: number; done: boolean; content: string; group: number; }; //定义Document属性 export type ItemDocument = mongoose.Document & ItemInterface; //创建Schema。第一个参数定义collection的构成。 //也就是说:该collection有这些属性,后续操作时作为限制条件 //第二个为可选选项 //versionKey为true时,添加文档会自动添加一项__v。 // _id为true,添加文档自动设置_id,类型为ObjectID //__v没用,_id自己设置,所以去除。 const ItemSchema = new mongoose.Schema( { _id: { type: Number, required: true }, user_id: { type: Number }, done: { type: Boolean }, content: { type: String }, group: { type: Number }, }, { versionKey: false, _id: false } ); //创建Model,第一个参数跟数据库collection名称相关。 //该参数结尾为数字,则该Model对应的collection为该参数的小写 //例如:"Item2"对应collection item2,该model的操作均会体现在item2上 //结尾为字母,则该Model对应的collection为该参数的小写的复数形式 //例如此处:"Item"对应collection items export const Item = mongoose.model<ItemDocument>('Item', ItemSchema);

    增删改查

    //以下指示例子,其他的参考文档 //增 const item = new Item(...); item.save((err, resItem) => {...}); //删 Item.deleteOne({ 搜索条件 }, (err) => {...}); //改 Item.updateOne({ 搜索条件 }, { 更新内容 }, (err) => {...}); //查 Item.findOne({ 搜索条件 },(err,res)=>{})

    聚合

    举例

    查找,改字段,过滤

    //查找user_id=0的文档,并修改_id为id,修改输入文档的结构 ModelItem.aggregate() .match({ user_id: 0 }) .project({ id: '$_id', done: 1, content: 1, group: 1, date: 1, _id: 0 }) .exec();

    查找所有_id符合groupIds中任何一个的文档,并修改_id,

    ModelGroup.aggregate() .match({ _id: { $in: groupIds, }, }) .project({ id: '$_id', title: 1, _id: 0 }) .exec();
    Processed: 0.012, SQL: 8