简体   繁体   English

MongoDb 和 Node.js

[英]MongoDb and Node.js

so I am working with node.js and mongodb and I am a rookie The below us my code:所以我正在与 node.js 和 mongodb 一起工作,我是菜鸟下面是我的代码:

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url,function(err,db){
 if (err){
     return console.dir(err);
 }
 console.log('connected to mdb');
 InsertDoc(db,function(){
  db.close(); 
 })
 });

 const InsertDoc= function(db, callback){

 const collection = db.collection('users');
 collection.insert({
     name : 'vishnu',
     email:'vishnu@123'
 },
 function(err,result){
     if(err){
         return console.dir(err);
     }
     console.log('inserted doc');
     console.log(result);
     callback(result);
 });
 }

 ERROR: TypeError: db.collection is not a function

I am not sure where I have gone wrong kindly let me know the mistake我不确定哪里出了问题,请告诉我错误

The callback from connect will return you an instance of MongoClient and an instance of Db , as mentioned in official Mongodb Node driver documentation, look at the second example来自connect的回调将返回一个MongoClient实例和一个Db实例,如官方 Mongodb 节点驱动文档中所述,请看第二个示例

https://mongodb.github.io/node-mongodb-native/4.1/classes/MongoClient.html https://mongodb.github.io/node-mongodb-native/4.1/classes/MongoClient.html

Once you obtain the collection you will have to get the db by using client.db(dbName) which will give you the db object for creating a collection .获得集合后,您将必须使用client.db(dbName)获取db ,这将为您提供用于创建collectiondb object。

// Connect using the MongoClient.connect static method
const MongoClient = require('mongodb').MongoClient;

// Connection url
const url = 'mongodb://localhost:27017/myproject';

// Connect using MongoClient
MongoClient.connect(url, function(err, client) {
  const db = client.db("myproject");

  const collection = db.collection("users");
  // do your thing

  client.close();
});
`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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