This article mainly introduces the installation under windows mongodb and the node.js connection to the mongodb instance. It is of great practical value. Friends who need it can refer to it.
1. MongoDB download
Download address https://www.mongodb.com/download-center# community Choose the Windows version to download and then install it.
2. Create the data directory after the installation is complete.
MongoDB stores the data directory under the db directory. However, this data directory will not be automatically created. We need to create it after the installation is completed. Please note that the data directory should be placed in the root directory (such as: C:\ or D:\, etc.). You can choose to create it through the command line or manually.
Finally generate such a directory
c:>data>db
##3. Run the MongoDB server under the command line
In order to run the MongoDB server from the command prompt, you must execute the mongod.exe file from the bin directory of the MongoDB directory, which is my installation path. Find the mongod.exe file in the path. Type the following code on the command linemongod.exe --dbpath c:\data\db
##Run successfully! 4. Configure the node.js project. The file structure is as follows:
## The entire code of app.js is as follows:
var MongoClient = require('mongodb').MongoClient , assert = require('assert'); // Connection URL var url = 'mongodb://localhost:27017/data'; // Use connect method to connect to the Server MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to server"); db.close(); });The entire package.json code is as follows: The main purpose is to install a mongodb so that you can operate higher-level APIs later. This is the address https://github.com/mongodb/node- mongodb-native
{ "name": "MongoDB", "version": "1.0.0", "description": "use MongoDB", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "mongodb" ], "author": "starwind", "license": "ISC", "dependencies": { "mongodb": "^2.2.26" } }Open the node.js command and execute
npm installin your own project path After installing the dependencies, run
node app.jsto see the output:
##Connection successful! #Note: If mongodb fails to start, configure the environment variables. This is my path: C:\Program Files\MongoDB\Server\3.4\bin. You can configure it according to your own installation directory.
The above is the detailed content of Installation mongodb example tutorial under windows. For more information, please follow other related articles on the PHP Chinese website!