Home  >  Article  >  Web Front-end  >  Example of how nodejs implements connection to mongodb database

Example of how nodejs implements connection to mongodb database

亚连
亚连Original
2018-05-30 10:42:012250browse

This article mainly introduces the method of nodejs to connect to the mongodb database, and analyzes the simple connection, query and shutdown of nodejs for the mongodb database in the form of examples. Friends in need can refer to this article

The example describes how nodejs implements connection to mongodb database. Share it with everyone for your reference, the details are as follows:


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(); //关闭链接
 });
});



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();//关闭链接
     });
  }
})

The above is what I compiled Everyone, I hope it will be helpful to everyone in the future.

Related articles:

jQuery implementation of news broadcast scrolling and fade-in and fade-out effects examples

Webpack's babel-loader file preset Detailed explanation of the processor

#Node.js method example to implement the registration email activation function

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

Statement:
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