Home > Web Front-end > JS Tutorial > How to connect nodejs to mongodb database

How to connect nodejs to mongodb database

小云云
Release: 2018-03-16 09:09:35
Original
1827 people have browsed it

This article mainly introduces the method of nodejs to connect to the mongodb database. It analyzes the simple connection, query and closing operation skills of nodejs for the mongodb database in the form of examples. Friends who need it can refer to it. I hope it can help everyone.


var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://zlg:437612lang@110.62.14.243:27017/lj_node';
MongoClient.connect(DB_CONN_STR, function(err, db) {
  if(err){console.log(err)} else{console.log("连接成功!");}
  //连接到表
  var collection = db.collection("lj_node");
 //查询数据
 collection.find().toArray(function(err, result) {
  if(err)
  {
   console.log('Error:'+ err);
   return;
  } else {
    console.log(result[0].name)
  }
  db.close(); //关闭链接
 });
});
Copy after login


mongodb.connect(mongodb_url,function(err,client){//创建链接实例
  if(err)
    console.log(err);
  else{
    var dbname="lj_node";
    var db=client.db(dbname);//创建数据库实例
    var collection = db.collection('lj_node');//创建表实例
    collection.find({}).toArray(function(err, docs) {//查询数据
      console.log(docs)
      client.close();//关闭链接
     });
  }
})
Copy after login

Related recommendations:

How to use Nodejs to connect to mongodb database tutorial detailed explanation

Yii framework code to connect mongodb database_php example

nodejs connects mongodb database to implement addition, deletion, modification and query

The above is the detailed content of How to connect nodejs to mongodb database. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template