简体   繁体   中英

connection to mongoDB

I am a new in nodeJS and mongodb. I can not connect my code with mongodb. here is my code. when I run this code it gives me this,

(node:9160) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect .

How can I fix it?

var express = require("express");
    var mongoose = require("mongoose");
    var passport = require("passport");
    var bodyParser = require("body-parser");
    var LocalStrategy = require("passport-local");
    var passportLocalMongoose = require("passport-local-mongoose");

    mongoose.connect("mongodb://localhost/mydb");

    // mongoose.connect("mongodb://localhost:27017/mydb_login", { useNewUrlParser: true })
    var app = express();

    app.set("view engine", "ejs");

Try it, I think it will help you.

let MONGOOSE = require('mongoose');    
MONGOOSE.connect('mongodb://127.0.0.1:27017/demo', (err, response)=>{
                if(err)
                    reject(err);
                else
                    resolve(null);
            });    

I would recommend to replace this statement of yours

mongoose.connect("mongodb://localhost/mydb");

with a one of this type:

mongoose.connect(uri)
.then(
    () => { 
      console.log("Connected");
    },
    err => {
      console.log(err); 
    }
);

This will help you to know wether the connection has been established or not and also if it is not established what is the corresponding error for the same.

just add {useNewUrlParser: true} to the connection options object

mongoose.connect("mongodb://localhost/mydb", { useNewUrlParser: true });

this is due to a new parser version

Put this code inside your layout file, not in app.js:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourDatabase', { useNewUrlParser: true });
var Schema = mongoose.Schema;

Then you can create your Schema layout, for example:

var mySchema = new Schema({
    first_name: String, 
    last_name: String
});

100% Work Method just Follow Me

  1. find The mongoose.connect(db) file in your project.... its could be found in Custom folder or server.js
  2. In mongoose.connect(db) replace mongoose.connect(db,{ useNewUrlParser: true })
  3. See image 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM