今天想安装一下MongoDB,中途遇到了不少困难,决定总结一下。
过程主要参考了mac 安装和使用MongoDB,前面按流程走就可以,但是在1.4步“在根目录下新建 data 文件夹”出现了问题,由于macOS Catalina版本开始根目录Macintosh HD变为只读,不再可写,导致无法新建文件夹,因此无法正常启动MongoDB。
$ mkdir -p /data/db
mkdir: /data/db: Read-only file system
更改数据库路径
研究了半天没有找到如何将根目录改为可写,决定想办法将默认路径“/data/db”更改到其他可写路径,如“/Users/lveshengyichou/data/db”,在终端输入如下代码:
$ mongod --dbpath=/Users/lveshengyichou/data/db
然后遇到如下报错:
2019-11-09T15:04:03.655+0800 E NETWORK [initandlisten] Failed to unlink socket file /tmp/mongodb-27017.sock Permission denied
2019-11-09T15:04:03.655+0800 F - [initandlisten] Fatal Assertion 40486 at src/mongo/transport/transport_layer_asio.cpp 693
2019-11-09T15:04:03.655+0800 F - [initandlisten]
***aborting after fassert() failure
注意报错中提到“Permission denied”,考虑到可能是权限问题,因此改为:
$ sudo mongod --dbpath=/Users/lveshengyichou/data/db
然后报错:
2019-11-09T15:05:46.642+0800 E STORAGE [initandlisten] Failed to set up listener: SocketException: Address already in use
2019-11-09T15:05:46.642+0800 I CONTROL [initandlisten] now exiting
2019-11-09T15:05:46.642+0800 I CONTROL [initandlisten] shutting down with code:48
直接Google报错内容,发现好像是我之前某次尝试启动MongoDB时,导致已经运行了一个mongod进程,首先查看一下运行中mongod的pid:
$ sudo lsof -iTCP -sTCP:LISTEN -n -P
在COMMAND列中找到mongod和它对应的PID以及TYPE,然后输入:
$ sudo kill <mongo_pid>
以终止mongod。
修改目录权限
再次执行:
$ sudo mongod --dbpath=/Users/lveshengyichou/data/db
报错again:
2019-11-09T15:15:36.584+0800 I STORAGE [initandlisten] exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory: /Users/lveshengyichou/data/db, terminating
2019-11-09T15:15:36.584+0800 I NETWORK [initandlisten] shutdown: going to close listening sockets...
2019-11-09T15:15:36.584+0800 I NETWORK [initandlisten] removing socket file: /tmp/mongodb-27017.sock
2019-11-09T15:15:36.584+0800 I - [initandlisten] Stopping further Flow Control ticket acquisitions.
2019-11-09T15:15:36.584+0800 I CONTROL [initandlisten] now exiting
2019-11-09T15:15:36.584+0800 I CONTROL [initandlisten] shutting down with code:100
貌似仍然是说目录不可写,Google后用如下方法将目录改为可写:
$ sudo chown -R $USER /data/db
再次启动mongod:
mongod --dbpath=/Users/lveshengyichou/data/db
这次终于成功了,但是后面出了很多warning,目前还不清楚是不是正常现象,总之是成功启动了!
参考文献:
[1] https://www.jianshu.com/p/7241f7c83f4a
[2] https://stackoverflow.com/questions/58034955/read-only-file-system-when-attempting-mkdir-data-db-on-mac
[3] https://stackoverflow.com/questions/47975929/socketexception-address-already-in-use-mongodb
[4] https://stackoverflow.com/questions/42446931/mongodb-exception-in-initandlisten-20-attempted-to-create-a-lock-file-on-a-rea