LoginSignup
1
0

More than 5 years have passed since last update.

[MAC] Node.js + MongoDB

Posted at

MacでNode.js+MongoDBを試してみた。
とても簡単に使えるようになりますね。

Install MongoDB

$ brew -v
Homebrew 1.7.6
$ brew update
$ brew install mongodb
$ mongo --version
MongoDB shell version v4.0.2

Case /data/db not found.

ガバいPermissionとかに抵抗なければシンボリックリンクを貼る。

$ sudo mkdir /data
$ sudo chmod 777 /data
$ ln -s /usr/local/var/mongodb /data/db
$ mongod --repair

Setup MongoDB for Node project.

$ node -v
v10.10.0
$ yarn -v
1.9.4
$ npm install -S mongodb

Node module

import { MongoClient } from 'mongodb';

const url = 'mongodb://localhost:27017/';

function insert(data) {
  console.log('[MongoModule] insert data:', data);
  MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    const dbo = db.db('testdb');
    dbo.collection('datas').insertOne(data, function (err, res) {
      if (err) throw err;
      console.log('[MongoModule] inserted. ', res);
      db.close();
    });
  });
}

module.exports = {
  insert: insert,
};

Check with Mongo.

$ mongo
> use testdb
> db.datas.find()
1
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
1
0