美文网首页
连接MongoDB

连接MongoDB

作者: 黑山老水 | 来源:发表于2017-08-25 09:19 被阅读26次

尝试用Mongoose连接MongoDB

  1. users里面建立src和test文件夹
  2. 在test里面建立test_helper.js文件进行连接测试

连接代码:

//set up

//import mongoose库
const mongoose = require('mongoose');

//告诉mongoose当前需要连接的数据库在哪。
//localhost: 在当前机器上,查找MongoDB.
//localhost 变成 port 比如:65.54.6.46:4000, 查找远程数据库
//users_test是自定义的MongoDB中多个数据库的一个
mongoose.connect('mongodb://localhost/users_test');

mongoose.connection //once和on都是event handler
//监听数据库发出的叫open的事件一次,然后调用一个函数
    .once('open', () => console.log('Good to go!'))
//监听数据库发出的叫error的事件,然后调用一个函数
    .on('error', (error) => {
        console.warn('Warning', error)
        });
  • Mongoose's default connection logic is deprecated as of 4.11.0.


    message
  • 修改代码:使用新的连接逻辑
mongoose.connect('mongodb://localhost/users_test', {
                 useMongoClient: true,
                 });
//The same is true for connect() and createConnection() if useMongoClient is true.

http://mongoosejs.com/docs/connections.html

相关文章

网友评论

      本文标题:连接MongoDB

      本文链接:https://www.haomeiwen.com/subject/tpoydxtx.html