Hướng dẫn html to mongodb
Tôi đang sử dụng nút js với express và Mongo. Tôi có một chương trình đơn giản đưa vào cài đặt người dùng thông qua các nút radio. Tôi có một nút gửi nhưng tôi không biết làm thế nào để làm cho nó hoạt động từ đó. Tôi có cần tệp JS mới để gửi đến mongodb không? Tất cả những gì tôi muốn là html của tôi để lưu các tùy chọn và lưu trữ chúng vào cơ sở dữ liệu. Tôi bắt đầu đi vào những bước nào? Show
Ví dụ ở đây: nếu tôi nhấp vào nam và nhấn gửi, tôi sẽ muốn từ nam lưu vào cơ sở dữ liệu.
7 hữu ích 1 bình luận 24k xem chia sẻ Đăng nhập để trả lời câu hỏiCó thể bạn quan tâmI am using node js with express and Mongo. I have a simple program that takes in user settings through radio buttons. I have a submit button but I do not know how to make it work from there. Do I need a new JS file to send it to mongodb? All I want is for my html to save the preferences and store them to the database. What steps do I start going in? Nội dung chính
Example here: if I clicked male and hit submit, I would want the word male to save to the database.
asked May 14, 2014 at 17:16 1 Creating a DatabaseTo create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create. MongoDB will create the database if it does not exist, and make a connection to it. ExampleCreate a database called "mydb": var MongoClient = require('mongodb').MongoClient; MongoClient.connect(url, function(err, db) { Run example » Save the code above in a file called "demo_create_mongo_db.js" and run the file: Run "demo_create_mongo_db.js" C:\Users\Your Name>node demo_create_mongo_db.js Which will give you this result: Important: In MongoDB, a database is not created until it gets content! MongoDB waits until you have created a collection (table), with at least one document (record) before it actually creates the database (and collection). Node.js can be used in database applications. One of the most popular NoSQL database is MongoDB. MongoDBTo be able to experiment with the code examples, you will need access to a MongoDB database. You can download a free MongoDB database at https://www.mongodb.com. Or get started right away with a MongoDB cloud service at https://www.mongodb.com/cloud/atlas. Install MongoDB DriverLet us try to access a MongoDB database with Node.js. To download and install the official MongoDB driver, open the Command Terminal and execute the following: Download and install mongodb package: C:\Users\Your Name>npm install mongodb Now you have downloaded and installed a mongodb database driver. Node.js can use this module to manipulate MongoDB databases: var mongo = require('mongodb'); MongoDB JavaScript tutoriallast modified June 16, 2022 MongoDB JavaScript tutorial shows how to do create programs that work with MongoDB in JavaScript. This tutorial uses the native mongodb driver. (There are also other solutions such as Mongoose or Monk.) MongoDB is a NoSQL cross-platform document-oriented database. It is one of the most popular databases available. MongoDB is developed by MongoDB Inc. and is published as free and open-source software. A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents. MongoDB stores documents in collections. Collections are analogous to tables in relational databases and documents to rows. Installing MongoDB serverThe following command can be used to install MongoDB on a Debian-based Linux. $ sudo apt-get install mongodb The command installs the necessary packages that come with MongoDB. $ sudo service mongodb status mongodb start/running, process 975 With the $ sudo service mongodb start mongodb start/running, process 6448 The MongoDB driver installWe set up the project. $ npm i mongodb We install the MongoDB create database The $ mongo testdb MongoDB shell version v4.0.7 ... > db testdb > db.cars.insert({name: "Audi", price: 52642}) > db.cars.insert({name: "Mercedes", price: 57127}) > db.cars.insert({name: "Skoda", price: 9000}) > db.cars.insert({name: "Volvo", price: 29000}) > db.cars.insert({name: "Bentley", price: 350000}) > db.cars.insert({name: "Citroen", price: 21000}) > db.cars.insert({name: "Hummer", price: 41400}) > db.cars.insert({name: "Volkswagen", price: 21600}) We create a MongoDB promisePromise is an object used for deferred and asynchronous computations. It represents an operation that has not completed yet, but is expected in the future. asyncFunc() .then(value => { /* success */ }) .catch(error => { /* failure */ }) .finally( => { /* cleanup */}; The Note: the We can also use MongoDB JS driverIn the first example, we print the version of the Node.js driver. driver_version.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; console.log(client.topology.clientInfo); client.close(); }); In the example, we connect to the server and find out the client information. const mongo = require('mongodb'); We use the const client = mongo.MongoClient; const url = 'mongodb://localhost:27017'; This is the URL to the database. The 27017 is the default port on which the MongoDB server listens. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { A connection to the database is created with $ node driver_version.js { driver: { name: 'nodejs', version: '3.2.2' }, os: { type: 'Windows_NT', name: 'win32', architecture: 'x64', version: '10.0.17134' }, platform: 'Node.js v11.5.0, LE' } The driver version is 3.2.2. MongoDB list database collections The list_collections.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); db.listCollections().toArray().then((docs) => { console.log('Available collections:'); docs.forEach((doc, idx, array) => { console.log(doc.name) }); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example connects to the db.listCollections().toArray().then((docs) => { console.log('Available collections:'); docs.forEach((doc, idx, array) => { console.log(doc.name) }); ... The Note: that we should be careful about using }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); In the Note: our applications are console programs; therefore, we close the connection at the end of the program. In web applications, the connections should be reused. $ node list_collections.js Available collections: continents cars cities In our database, we have these three collections. MongoDB database statistics The dbstats.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); db.stats((err, stats) => { if (err) throw err; console.log(stats); client.close(); }) }); The example connects to the $ node dbstats.js { db: 'testdb', collections: 3, views: 0, objects: 18, avgObjSize: 57.888888888888886, dataSize: 1042, storageSize: 69632, numExtents: 0, indexes: 3, indexSize: 69632, fsUsedSize: 136856346624, fsTotalSize: 254721126400, ok: 1 } MongoDB find The find_all.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); db.collection('cars').find({}).toArray().then((docs) => { console.log(docs); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); });
In the example, we retrieve all docs from db.collection('cars').find({}).toArray().then((docs) => { Passing an empty query returns all documents. $ node find_all.js [ { _id: 5cfcfc3438f62aaa09b52175, name: 'Audi', price: 52642 }, { _id: 5cfcfc3a38f62aaa09b52176, name: 'Mercedes', price: 57127 }, { _id: 5cfcfc3f38f62aaa09b52177, name: 'Skoda', price: 9000 }, { _id: 5cfcfc4338f62aaa09b52178, name: 'Volvo', price: 29000 }, { _id: 5cfcfc4838f62aaa09b52179, name: 'Bentley', price: 350000 }, { _id: 5cfcfc4b38f62aaa09b5217a, name: 'Citroen', price: 21000 }, { _id: 5cfcfc4f38f62aaa09b5217b, name: 'Hummer', price: 41400 }, { _id: 5cfcfc5438f62aaa09b5217c, name: 'Volkswagen', price: 21600 } ] MongoDB count documents The count_documents.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); db.collection('cars').find({}).count().then((n) => { console.log(`There are ${n} documents`); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example counts the number of documents in the $ node count_documents.js There are 8 documents There are eight documents in the cars collection now. MongoDB findOne The find_one.js const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); let collection = db.collection('cars'); let query = { name: 'Volkswagen' } collection.findOne(query).then(doc => { console.log(doc); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example reads one document from the let query = { name: 'Volkswagen' } The query contains the name of the car—Volkswagen. collection.findOne(query).then(doc => { The query is passed to the $ node find_one.js { _id: 8, name: 'Volkswagen', price: 21600 } MongoDB async/await example With async_await.js const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; async function findCar() { const client = await MongoClient.connect(url, { useNewUrlParser: true }) .catch(err => { console.log(err); }); if (!client) { return; } try { const db = client.db("testdb"); let collection = db.collection('cars'); let query = { name: 'Volkswagen' } let res = await collection.findOne(query); console.log(res); } catch (err) { console.log(err); } finally { client.close(); } } findCar(); The example reads one document using async function findCar() { The function has the let res = await collection.findOne(query); With MongoDB query operators It is possible to filter data using MongoDB query operators such as
read_gt.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); let query = { price: { $gt: 30000 } }; db.collection('cars').find(query).toArray().then((docs) => { console.log(docs); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example prints all documents whose car prices' are greater than 30,000. let query = { price: { $gts: 30000 } }; The $ node read_gt.js [ { _id: 5d03e40536943362cffc84a7, name: 'Audi', price: 52642 }, { _id: 5d03e40a36943362cffc84a8, name: 'Mercedes', price: 57127 }, { _id: 5d03e41936943362cffc84ab, name: 'Bentley', price: 350000 }, { _id: 5d03e42236943362cffc84ad, name: 'Hummer', price: 41400 } ] This is the output of the example. Only cars more expensive than 30,000 are included. The read_gt_lt.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); let query = { $and: [{ price: { $gt: 20000 } }, { price: { $lt: 50000 } }] }; db.collection('cars').find(query).toArray().then((docs) => { console.log(docs); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); In the example, we retrieve cars whose prices fall between 20,000 and 50,000. let query = { $and: [{ price: { $gt: 20000 } }, { price: { $lt: 50000 } }] }; The $ node read_gt_lt.js [ { _id: 5d03e41336943362cffc84aa, name: 'Volvo', price: 29000 }, { _id: 5d03e41e36943362cffc84ac, name: 'Citroen', price: 21000 }, { _id: 5d03e42236943362cffc84ad, name: 'Hummer', price: 41400 }, { _id: 5d03e42636943362cffc84ae, name: 'Volkswagen', price: 21600 } ] MongoDB projectionsProjections determine which fields are passed from the database. projections.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); db.collection('cars').find({}).project({_id: 0}).toArray().then((docs) => { console.log(docs); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example excludes the db.collection('cars').find({}).project({_id: 0}).toArray().then((docs) => { The $ node projections.js [ { name: 'Audi', price: 52642 }, { name: 'Mercedes', price: 57127 }, { name: 'Skoda', price: 9000 }, { name: 'Volvo', price: 29000 }, { name: 'Bentley', price: 350000 }, { name: 'Citroen', price: 21000 }, { name: 'Hummer', price: 41400 }, { name: 'Volkswagen', price: 21600 } ] This is the output for the example. MongoDB limit data output The skip_limit.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); db.collection('cars').find({}).skip(2).limit(5).toArray().then((docs) => { console.log(docs); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example reads from the db.collection('cars').find({}).skip(2).limit(5).toArray().then((docs) => { The $ node skip_limit.js [ { _id: 5d03e40f36943362cffc84a9, name: 'Skoda', price: 9000 }, { _id: 5d03e41336943362cffc84aa, name: 'Volvo', price: 29000 }, { _id: 5d03e41936943362cffc84ab, name: 'Bentley', price: 350000 }, { _id: 5d03e41e36943362cffc84ac, name: 'Citroen', price: 21000 }, { _id: 5d03e42236943362cffc84ad, name: 'Hummer', price: 41400 } ] MongoDB aggregationsAggregations calculate aggregate values for the data in a collection. sum_all_cars.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); let myagr = [{$group: {_id: 1, all: { $sum: "$price" } }}]; db.collection('cars').aggregate(myagr).toArray().then((sum) => { console.log(sum); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example calculates the prices of all cars in the collection. let myagr = [{$group: {_id: 1, all: { $sum: "$price" } }}]; The db.collection('cars').aggregate(myagr).toArray().then((sum) => { The $ node sum_all_cars.js [ { _id: 1, all: 581769 } ] The sum of all prices is 581,769. We can use the sum_two_cars.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); let myagr = [ { $match: { $or: [{ name: "Audi" }, { name: "Volvo" }] } }, { $group: { _id: 1, sum2cars: { $sum: "$price" } } } ]; db.collection('cars').aggregate(myagr).toArray().then((sum) => { console.log(sum); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example calculates the sum of prices of Audi and Volvo cars. let myagr = [ { $match: { $or: [{ name: "Audi" }, { name: "Volvo" }] } }, { $group: { _id: 1, sum2cars: { $sum: "$price" } } } ]; The expression uses $ node sum_two_cars.js [ { _id: 1, sum2cars: 81642 } ] The sum of the two cars' prices is 81,642. MongoDB insertOne The insert_one.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const ObjectID = mongo.ObjectID; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); let doc = {_id: new ObjectID(), name: "Toyota", price: 37600 }; db.collection('cars').insertOne(doc).then((doc) => { console.log('Car inserted') console.log(doc); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example inserts one car into the cars collection. let doc = {_id: new ObjectID(), name: "Toyota", price: 37600 }; This is a document to be inserted. A new Id is generated with db.collection('cars').insertOne(doc).then((doc) => { The > db.cars.find({name:'Toyota'}) { "_id" : ObjectId("5d03d4321f9c262a50e671ee"), "name" : "Toyota", "price" : 37600 } We confirm the insertion with the MongoDB insertMany The insert_many.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const ObjectID = mongo.ObjectID; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); let collection = db.collection('continents'); let continents = [ { _id: new ObjectID(), name: "Africa" }, { _id: new ObjectID(), name: "America" }, { _id: new ObjectID(), name: "Europe" }, { _id: new ObjectID(), name: "Asia" }, { _id: new ObjectID(), name: "Australia" }, { _id: new ObjectID(), name: "Antarctica" } ]; collection.insertMany(continents).then(result => { console.log("documents inserted into the collection"); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example creates a let collection = db.collection('continents'); The let continents = [ { _id: new ObjectID(), name: "Africa" }, { _id: new ObjectID(), name: "America" }, { _id: new ObjectID(), name: "Europe" }, { _id: new ObjectID(), name: "Asia" }, { _id: new ObjectID(), name: "Australia" }, { _id: new ObjectID(), name: "Antarctica" } ]; This is an array of six records to be inserted into the new collection. The collection.insertMany(continents).then(result => { console.log("documents inserted into the collection"); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); The > db.continents.find() { "_id" : ObjectId("5cfcf97732fc4913748c9669"), "name" : "Africa" } { "_id" : ObjectId("5cfcf97732fc4913748c966a"), "name" : "America" } { "_id" : ObjectId("5cfcf97732fc4913748c966b"), "name" : "Europe" } { "_id" : ObjectId("5cfcf97732fc4913748c966c"), "name" : "Asia" } { "_id" : ObjectId("5cfcf97732fc4913748c966d"), "name" : "Australia" } { "_id" : ObjectId("5cfcf97732fc4913748c966e"), "name" : "Antarctica" } The MongoDB deleteOne The delete_one.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); let query = { name: "Volkswagen" }; db.collection('cars').deleteOne(query).then((result) => { console.log('Car deleted'); console.log(result); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example deletes a document. let query = { name: "Volkswagen" }; db.collection('cars').deleteOne(query).then((result) => { ... The MongoDB updateOne The update_one.js const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { if (err) throw err; const db = client.db("testdb"); let filQuery = { name: "Audi" }; let updateQuery = { $set: { "price": 52000 }}; db.collection('cars').updateOne(filQuery, updateQuery).then(result => { console.log('Car updated'); console.log(result); }).catch((err) => { console.log(err); }).finally(() => { client.close(); }); }); The example updats a prices of a car. let filQuery = { name: "Audi" }; let updateQuery = { $set: { "price": 52000 }}; db.collection('cars').updateOne(filQuery, updateQuery).then(result => { The price of Audi is changed to 52,000 with the > db.cars.find({name:'Audi'}) { "_id" : ObjectId("5cfcfc3438f62aaa09b52175"), "name" : "Audi", "price" : 52000 } We confirm the changes with the In this article, we have worked with MongoDB and JavaScript. List all JavaScript tutorials. Can I use MongoDB for my website?MongoDB is general-purpose The database can be used for several web applications, including customer data management, content management, data hubs, mobile apps, Internet of Things, Big Data, product and asset catalogs and database-as-a-service. Can I use MongoDB in frontend?Short answer: You don't. Long answer: MongoDB isn't designed to expose data directly to the client. The client interacts with the application on the webserver - in your case implemented in Node. js - and the webserver communicates with the database. How fetch data from MongoDB and display in HTML?How to Fetch Data From mongodb in Node js and Display in HTML (ejs). Step 1 – Create Node Express js App.. Step 2 – Install express flash ejs body-parser mongoose dependencies.. Step 3 – Connect App to MongoDB.. Step 4 – Create Model.. Step 5 – Create Routes.. Step 6 – Create HTML Table and Display List.. Is MongoDB good for web development?MongoDB is a fast and reliable database that is one of the recommended databases in designing scalable web applications that required the storage of unstructured data. |