search

Home  >  Q&A  >  body text

Problem with mongodb connecting to localhost database

You can connect to the database locally;

import * as mongoose from 'mongoose';

/**
 * 连接
 */
mongoose.connect(`mongodb://127.0.0.1:27017`);

/**
 * 连接成功
 */
mongoose.connection.on('connected', function () {
    console.log('数据库连接成功');
});

/**
 * 连接异常
 */
mongoose.connection.on('error',function (err) {
    console.log('数据库连接出现错误,错误为:'+ err);
});

/**
 * 连接断开
 */
mongoose.connection.on('disconnected', function () {
    console.log('数据库连接断开');
});

module.exports = mongoose;

Connecting through the above code prompts:

PHPzPHPz2793 days ago1219

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-05-02 09:28:25

    The connection string of connect in your code is wrong. It should be:

    mongoose.connect('mongodb://localhost/test');

    means connecting to the test database; if the port number is default, it can be omitted.

    Cracked Wall recommends reading the documentation on the mongoose website. Some blog posts about mongoose contain errors.

    http://mongoosejs.com/

    For reference.

    Love MongoDB! Have fun!


    See you there on the 19th, please click: >---<

    MongoDB Online Lecture Series 19- MongoDB 10 steps to build a single view

    reply
    0
  • Cancelreply