【mongoDB】Mongoose备忘单

猫鼬指的是什么?

可以构建具有定义保存哪种类型数据的”模式”的模型。
模型类似于JavaScript中的类。
使用Mongoose的模型可以组织数据库查询。

经常使用的查询方法

find : マッチするドキュメントの配列を返す

Human.find({name:"taro" }, (err, result)=> {
  //処理結果
});

findOne: 返回一个不是数组而是一个文档。例如:Human.findOne({name: “Taro”})

findById: 返回与给定的ObjectIde相匹配的对象。例如:Human.findOne(“kjfkajjdfkjagkja”)

remove: 删除数据库中的文档。

find().pretty(): 通过添加.pretty()来对结果进行缩进。

这些查询返回的是一个Promise,所以在结果处理中需要使用then或catch进行连接。

在Node.js应用程序中配置Mongoose。

//mongooseをロード
const mongoose = require("mongoose");
//データーベース接続を設定
mongoose.connect(
  "mongodb://<username>:<password>@localhost:27017/<dbname>",
  {userNewParser:true}
);

mongoose.set("useCreateIndex", true);

//データーベースをdb変数に代入
const db = mongoose.connection;

//接続メッセージをログに出力する
db.once("open",()=>{
  console.log("success connect");
});

创建模式

通过在mongoose.Schema方法的构造函数中提供参数(对象),可以构建模式对象。

const mongoose = require("mongoose");
const humanSchema = new mongoose.Schema({
  name:String,
  age:Number
});

关于模式数据类型

设定虚拟属性

const humanSchema = new mongoose.Schema({
  name:String,
  age:Number
});

humanSchema.virtual("info").get(function () { //実際の属性としてはデーターベースに保存されないが、インスタンスから取り出せる。
  return `${this.name} ${this.age}`;
});

设定验证

"use strict";

const mongoose = require("mongoose");

const humanSchema = new mongoose.Schema({
  name: {  //nameのバリューにオブジェクトで渡す。
    type: String,
    required: true,  //必須
    unique: true     //ユニーク
  },
  age: {
    type: Number,
    min: [18, "Too short"],//最小値エラーメッセージ を設定
    max: 99 //最大値
  }
});

module.exports = mongoose.model("Human", humanSchema);

将模式应用于模型。

const Human = mongoose.model("Human", humanSchema)
//mongoose.modelメソッドに("モデル名", スキーマ)を引数に与えて、実体化してHumanに格納する。

出口

module.exports = mongoose.model("Human", humanSchema);

在模式中设置实例方法(设置名为”getInfo”的方法)。

humanSchema.methods.getInfo = function () {
  return `Name: ${this.name} Age: ${this.age}`;
};

从模型创建对象。

新的 → 保存的方式

let human1 = new Human({ //newキーワードでオブジェクトを生成。
  name: "Taro",
  age:20
});
human1.save((error, savedDocument) => {  //saveメソッドで保存
  //引数に、エラー処理、または返されるデーターの処理をコールバック関数で渡す。
  if (error){
   console.log(error)
  }
  console.log(savedDocument);

创建的方法

Human.create({
  name: "Taro",
  age:20
  },
  function(error,savedDocument){
  if (error){
   console.log(error)
  }
  console.log(savedDocument);
  }
};
//createは、newとsaveを一気に行う。(パラメータ, コールバック)が引数。

设置钩子。

humanSchema.pre("save", function(next) {
  //saveされる前に実施する処理
  //この中でのthisは呼び出し元、つまりhumanSchemaが格納される。
  next();
}

将模型进行组织化

在模型文件中定义模式和模型。

const mongoose = require("mongoose");

const humanSchema = mongoose.Schema({ //mongoose.Schemaメソッドでスキーマを作る
  name:String,
  age:Number
});

module.exports = mongoose.model("Human", humanSchema); 
//mongoose.modelメソッドでスキーマをHumanモデルに適用しエクスポート

从其他文件中调用Human模型。

const Human = require("./models/human");

建立模型之间的关系

"use strict";

const mongoose = require("mongoose");

const humanSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  age: {
    type: Number,
    min: [18, "Too short"],
    max: 99 //最大値
  }
  father: { //Fatherモデルに所属//単数形
    type: mongoose.Schema.Types.ObjectId, //外部キー
    ref: "Father" //参照モデル
    }
  children: [{ //Childモデルを所有//複数形//配列リテラルで囲む
    type: mongoose.Scheme.Types.ObnectId,
    ref: "Child"
    }]
});

module.exports = mongoose.model("Human", humanSchema);

实际上将文档互相关联

//所有の場合
human1.children.push(child1);
human1.save();
 //human1インスタンスのchildrenプロパティにchild1ドキュメントを追加
//もしくは、直接ObjectIDを追加する。
human1.children.push("オブジェトID");
human1.save();

//所属の場合
human1.father = father1;
human1.save();

获取相关的文件。

Human.populate(human1, "children"); //human1に紐づくchildドキュメントを連結してオブジェクト化する。

选择关联的文件,并指定相关联的亲属。

Human.findOne({ name: "taro" }).populate({"children" }).exec((error, data) => {
  console.log(data);
}
)

在数据库中搜索文档。

const Human = require("./models/human");

Human.findOne({name:"Taro"}).where("age":20);
//findOne(合致するものを取得).where(絞り込み条件);

执行查询

let query = Human.findOne({name:"Taro"}).where("age":20);

query.exec((error, data)=>{  //execで実行し、処理を引数にとる。返るデータはdataに渡す。
  if(data){
    console.log(data.name)
  }
);

同时进行搜索和更新

 <モデル>.findByIdAndUpdate(<id>, {
      $set: <オブジェクト>//$setのバリューの値でアップデート
    })

同时进行搜索和删除

<モデル>.findByIdAndRemove(<id>)

使用Promise的设置

mongoose.Promise = global.Promise

创建种子模块

const mongoose = require("mongoose"); //モジュールロード

const Human = require("./models/Human.js");
//保存するモデルの読み込み必要

mongoose.connect(  //接続設定
  "mongodb://localhost:27017/my_db",
  {userNewParser:true}
);

mongoose.set("useCreateIndex", true);

mongoose.connection;

const humans = [ //シードデーター
  {name:"Taro",
   age:20
  },
  {name:"Ken",
   age:30
  },
  {name:"Jiro",
   age:40
  }
];

Human.deleteMany() //既存のデータをクリア
  .exec()
  .then(() => {
     console.log("Empty"); //確認用ログ
  });

let commands = []; //シーダー配列用

humans.forEeach((c)=> { //commands配列にシーダーをループで全て追加
  commands.push(Human.create({
    name:c.name,
    email:c.age
    }));
});

Promise.all(commands) //全てのプロミス解決後の処理
  .then(r => {
    console.log(JSON.stringify(r));
    mongoose.connection.close();
  })
  .catch(error => {
    console.log($error);
});
广告
将在 10 秒后关闭
bannerAds