javascript 如何将MongoDB与Node.js一起使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 如何将MongoDB与Node.js一起使用相关的知识,希望对你有一定的参考价值。

const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;

//URL to the mongo server
const url = "mongodb://localhost:27017";
 
MongoClient.connect(url, function(error, client){
    if(error){
        console.log("Problem connecting to server.");
    }else{
        console.log("Connected to server");

        //Connect to a database
        var humansDB = client.db("humans");

        //Connect to the people collection
        var peopleCollection = humansDB.collection("people");

        //Insert a document into the collection
        peopleCollection.insertOne({
            name: "Bobby",
            age: "500",
            weight: 130
        });

        //List all of the documents in the people collection
        var data = peopleCollection.find({}).toArray(function(error, data){
            if(error){
                console.log("Error getting data");
            }else{
                console.log(data);
            }
        });

        //Close the connection
        client.close();

    }
});

app.listen(3000, () => console.log('Listening on port 3000!'));

以上是关于javascript 如何将MongoDB与Node.js一起使用的主要内容,如果未能解决你的问题,请参考以下文章