0
0

MongoDBの学習で詰まったので振り返り

Posted at

はじめに

Kindle Unlimitedで三好アキさんの
「はじめてつくるバックエンドサーバー 発展編」
を学習していました。
この著者の方の本は解説が分かりやすく丁寧なのでおすすめです。

ただ、この本が出たとき(2021年)と今でMongoDBの仕様が変わったようで、
実行できない箇所があり詰まりました。

将来、同じ箇所で詰まるのも嫌なのでメモとして残します。

該当箇所

この本の中に下記のコードがあります。

これを実行すると

app.post('/blog/create', async (req, res) => {
	console.log('reqの中身', req.body);
	BlogModel.create(req.body, (error, savedBlogData) => {
		if (error) {
			console.log('データの書き込みに失敗しました。');
			res.send('ブログデータの投稿に失敗しました。');
		} else {
			console.log('データの書き込みが成功しました。');
			res.send('ブログデータの投稿が成功しました。');
		}
	});
});

createはコールバック関数を受け付けていないというエラーがでました。
MongoDBのバージョンアップにより、コールバック関数は使用不可となったようです。

MongooseError: Model.create() no longer accepts a callback
    at Function.create 

なので、コールバック関数ではなく、async awaitの非同期処理の構文に書き換える必要がありました。

app.post('/blog/create', async (req, res) => {
	console.log('reqの中身', req.body);
	try {
		const savedBlogData = await BlogModel.create(req.body);
		console.log('投稿に成功しました。');
		res.send('ブログデータを投稿しました。');
	} catch (error) {
		console.log('投稿に失敗しました。');
		console.log(error);
		res.status(500).send('ブログデータの投稿に失敗しました。');
	}
});

また、これはちょっと違う件で、MongoDBの接続を公式サイトから丸々コピーしたのですが、動きませんでした。

const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://user:<password>@cluster0.wb8mqjn.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  }
});
async function run() {
  try {
    // Connect the client to the server	(optional starting in v4.7)
    await client.connect();
    // Send a ping to confirm a successful connection
    await client.db("admin").command({ ping: 1 });
    console.log("Pinged your deployment. You successfully connected to MongoDB!");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

これでデータを書き込もうとすると下記のタイムアウトエラーが発生しました。

Pinged your deployment. You successfully connected to MongoDB!
reqの中身 { title: '', summary: '', image: '', textBody: '' }
投稿に失敗しました。
MongooseError: Operation `blogs.insertOne()` buffering timed out after 10000ms

これを下記にしたら動きました。

// const client = new MongoClient(uri, {
// 	serverApi: {
// 		version: ServerApiVersion.v1,
// 		strict: true,
// 		deprecationErrors: true,
// 	},
// });
// async function run() {
// 	try {
// 		await client.connect();
// 		await client.db('admin').command({ ping: 1 });
// 		console.log('Pinged your deployment. You successfully connected to MongoDB!');
// 	} finally {
// 		await client.close();
// 	}
// }
// run().catch(console.dir);

// 下記に変更
mongoose
	.connect(uri, {
		connectTimeoutMS: 30000,
	})
	.then(() => {
		console.log('Connected to MongoDB');
	})
	.catch((error) => {
		console.error('MongoDB connection error:', error);
	});

DBに書き込みが成功しました。

Pinged your deployment. You successfully connected to MongoDB!
reqの中身 { title: '', summary: '', image: '', textBody: '' }
投稿に成功しました。

細かい内容の解説は成長した自分に任せるとして、とりあえず動いたのでヨシ!とします。

さいごに

三好アキさんの著書本当におすすめです!
とりあえずNode.js触ってみたい方や苦手意識があるかたでも苦なく環境構築 & アプリの作成ができます。
kindle Unlimitedはこういう良書がたくさんあるのでおすすめです。

こんな宣伝しても一銭も自分に入らないんですけどね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0