Mongoose Express CRUD

const mongoose = require("mongoose");
const conn_str = "mongodb://localhost:27017/tcet"
mongoose.connect(conn_str, { useNewUrlParser: true , useUnifiedTopology: true})
	.then( () => console.log("Connected successfully...") )
	.catch( (err) => console.log(err) );

const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	city: String,
	state: String
});

const user = new mongoose.model("user", userSchema);

/** Express Mongoose Integration **/

const express = require("express");
const app = express();

app.route("/user")
.get(async (req, res) => {
	let data = await user.find();
	res.send(data);
})
.post(async (req, res) => {
	req_data = req.query;
	let obj = new user(req.query)
	let result = await obj.save();
	res.send(result);
})
.put(async (req, res) => {
	req_data = req.query;
	let result = await user.updateOne({_id: req.query.id}, {$set : {city: req.query.city}})
	res.send(result);
})
.delete(async (req, res) => {
	let result = await user.deleteOne({_id: req.query.id})
	res.send(result);
})

app.listen(8080, () => {
	console.log("listening 8080...");
});

Connect to MongoDB Atlas Cluster

Whitelist your ip / or allow from all 0.0.0.0/0

Get Your Current IP Address from google > what is my ip

Atlas > Security > Network Access > ADD IP ADDRESS

First get the connection string or URI from Atlas

Atlas > Deployment > Databases > Connect > Connect your application > Driver Node.js > Version 2.2.12 or later
const port = 8080;
const mongoose = require("mongoose");
const uri ="get_uri_from_atlas"
mongoose.connect(uri, { useNewUrlParser: true , useUnifiedTopology: true})
	.then( () => console.log("Connected successfully...") )
	.catch( (err) => console.log(err) );

const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	city: String
});

const user = new mongoose.model("users", userSchema);

/** Express Mongoose Integration **/

const express = require("express");
const app = express();

app.route("/user")
.get(async (req, res) => {
	let data = await user.find();
	res.send(data);
})
.post(async (req, res) => {
	req_data = req.query;
	let obj = new user(req.query)
	let result = await obj.save();
	res.send(result);
})
.put(async (req, res) => {
	req_data = req.query;
	let result = await user.updateOne({_id: req.query.id}, {$set : {city: req.query.city}})
	res.send(result);
})
.delete(async (req, res) => {
	let result = await user.deleteOne({_id: req.query.id})
	res.send(result);
})

app.listen(process.env.PORT || port, () => {
	console.log("listening 8080...");
});

16 Replies to “Mongoose Express CRUD”

  1. Today, I went to the beach with my kids. I found
    a sea shell and gave it to my 4 year old daughter and
    said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her ear. She never wants to go back!

    LoL I know this is entirely off topic but I had to tell someone!

  2. At this time it appears like BlogEngine is the top blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

  3. This is a very good tip particularly to those fresh to the blogosphere. Short but very accurate information… Thank you for sharing this one. A must read article!

  4. I loved as much as you will receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an shakiness over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this increase.

  5. Приветствую! Сегодня затронем тему про кровельные работы. Лично я понял: хочешь надёжно — вот проверенные ребята: https://montazh-membrannoj-krovli-spb.ru. Суть в том, что: крыша без уклона — это особая технология. Вот, то есть плохой водоотвод — слышишь постоянно про лужи? Значит монтаж был неправильный. Мы используем клиновидный утеплитель, сверху — ПВХ мембрану. Опять же высокоэффективный инструмент. Резюмируем: никаких луж и протечек.

  6. Привет всем! Стоит заранее разобрать — гидроизоляция склада. Нет времени искать — могу рекомендовать проверенную компанию: установка мембранной кровли. На практике большие площади — нуждаются в профессионалах. Например, площадь 1000+ квадратов — то есть важен опыт бригады. Можно поставить автоматические сварочные аппараты. Вот потому что это работает. Вместо заключения: крыша сдаётся с гарантией.

  7. For those seeking an exceptional online gaming experience, us.com](https://maxispin.us.com/) stands out as a premier destination. At Maxispin Casino, players can enjoy a vast array of pokies, table games, and other thrilling options, all accessible in both demo and real-money modes. The casino offers attractive bonuses, including free spins and a generous welcome offer, along with cashback promotions and engaging tournaments. To ensure a seamless experience, Maxispin provides various payment methods, efficient withdrawal processes, and reliable customer support through live chat. Security is a top priority, with robust safety measures and a strong focus on responsible gambling tools. Players can easily navigate the site, with detailed guides on account creation, verification, and payment methods. Whether you’re interested in high RTP slots, hold and win pokies, or the latest slot releases, Maxispin Casino delivers a user-friendly and secure platform. Explore their terms and conditions, read reviews, and discover why many consider Maxispin a legitimate and trustworthy choice in Australia.
    The user-friendly nature of the platform ensures it is accessible to all users.

    **Features of MaxiSpin.us.com**
    The platform also includes a built-in editor, enabling on-the-spot adjustments for optimal results.

    **Benefits of Using MaxiSpin.us.com**
    The platform is also cost-effective, providing high-quality content at a fraction of the cost of traditional methods.

Leave a Reply to hi88 Cancel reply

Your email address will not be published.