I wrote a little of code to start learning MongoDB with Node.js in JavaScript but it doesn't work but it doesn't
give a error while running probably someone can help me with that.
The Main code:
const mongoose = require('mongoose');
const express = require('express');
const test = express();
const Blog = require('./bdSchema');
//connec to mongodb
const dbURI = 'mongodb+srv://Carsten:<int the real code the password is here>#cluster0.w6iwv.mongodb.net/tomhatesgeschaft?retryWrites=true&w=majority';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => console.log("connected to db"))
.catch((err) => console.log(err))
test.get('/add-tomhatesgeschaft', (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
tomhatesgeschaft.save()
.then((result) => {
res.send(result)
})
.catch((err) => {
console.log(err);
});
})
The BDSchema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BDSchema = new Schema({
title: {
type: String,
required: true,
},
});
const Blog = mongoose.model('Blog', BDSchema);
module.exports = Blog;
In your Node.js code, change the save function as below.
tomhatesgeschaft.save((err,result) => {
if (err){
console.error(err);
}
else{
res.send(result)
})
})
OR
test.get('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})
PS: You should not use GET requests for operations such as saving data to the database. Ideally, you should use a POST request.
Example with async:
test.post('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})
Related
I'm having trouble capturing the current collection in mongodb.
I have a file with FetchUsers function which returns a collection with users:
const mongoose = require('mongoose');
const uri = "mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const fetchUsers= () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try{
mongoose.connect(uri);
} catch (error)
{
console.log(error);
}
const collectionName = 'UsersTests'
const Users = mongoose.model(collectionName, new mongoose.Schema({}));
Users .find({}, function(err, docs) {
if (err) {
console.error(err);
return;
}
console.log(`Documents in ${collectionName}:`);
mongoose.connection.close();
console.log(`My current collection: ${docs}`);
return docs;
});
}
module.exports = fetchUsers
In another file I have a function that takes the returned value and then displays it:
const fetchData = require("../../controllers/USersControllers/fetchUsers.js");
async function displayUsers() {
let users = await fetchData();
console.log(users);
}
module.exports = displayUsers;
and all this is running on the express server
const express = require("express");
const displayUsers = require("./public/js/displayUsers.js");
const app = express();
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.listen(5000, () => {
console.log("Server started on port 3000");
displayUsers();
});
The problem is that displayUsers displays undefined and doesn't wait until fetchData returns a collection.
OK, I corrected the code and it works.
GetUsersModel.js:
const mongoose = require("mongoose");
const uri =
"mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
try {
mongoose.connect(
uri
);
console.log("Database conected!");
} catch (error) {
console.log(error);
console.log("Database connection failed");
}
const Schema = new mongoose.Schema({
content: String,
title: String,
author: String,
});
const Users =
mongoose.model.userTest ||
mongoose.model("userTest", Schema);
module.exports = Users;
fetchUsersData.js
const mongoose = require('mongoose');
const Users =
require("../controllers/SnippetsControllers/GetSnippetModel.js");
const uri =
"mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const fetchUsers = () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try{
mongoose.connect(uri);
console.log('Database conected!!!!!')
} catch (error)
{
console.log(error);
console.log('Database connection failed')
}
return new Promise((resolve, reject) => {
Users.find({}, function(err, docs) {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
});
}
module.exports = fetchUsers;
UseUsersData.js
const fetchData = require("../models/fetchUsersData");
async function displayUsers(req) {
let usersContainer = [];
try {
let users = await fetchData();
let usersArray = users;
console.log(usersArray);
} catch (error) {
console.log(error);
}
}
I have been learninng NodeJS and mongoDB by youtube, but unfortunately i faced with this problem, and here is my code file! thank you in advance!
db.js
const { MongoClient } = require("mongodb");
let dbConnection;
module.exports = {
connectToDb: (cb) => {
MongoClient.connect("mongodb://localhost:27017/bookstore")
.then((res) => {
dbConnection = res.db();
return cb();
})
.catch((error) => {
console.log(error);
return cb(error);
});
},
getDb: () => dbConnection,
};
index.js
const express = require("express");
const { connectToDb, getDb } = require("./db");
// init app and middleware
const app = express();
//db connection
let db;
connectToDb((xato) => {
if (!xato) {
app.listen(3000, () => {
console.log("The 3000 port is installed");
});
db = getDb();
return db;
}
});
//routes
app.get("/bookstore", (req, res) => {
let mybook = [];
// the collection name from mongoDB
db.collection("bookstore")
.find()
.sort({ author: 1 })
.forEach((book) => mybook.push(book))
.then(() => {
return res.sendStatus(200).json(mybook);
})
.catch(() => {
return res.sendStatus(500).send("there were an error");
});
// res.json({ MyWords: "I am coming from json res" });
});
it must return data from local mongodb database. But it is facing with the problem. Please give me a solution!
both .sendStatus and .json will try to response to client. So the second call will result in this error.
Just use res.json(mybook) and res.send("there were an error") is enough.
In case you want to maintain status code and also send data. Use res.status(500).send("there were an error").
I am trying to access the user with _id in node js and mongodb. I have successfully connected to the database and i am using the same user id as in mongodb compass but it is giving me null in my console. Any help in the matter?
regards
const mongodb = require('mongodb');
const getDb = require('../util/database').getDb;
const ObjectId = mongodb.ObjectId;
static findById(userId) {
const db = getDb();
return db
.collection('users').findOne({ _id: new ObjectId(userId) }).then(user => {
return user;
})
.catch(err => {
console.log(err);
});
}
}
Here is the app.js
app.use((req, res, next) => {
User.findById('637135a7bf28b66e21340c2f').then(user => {
req.user = user
console.log(user)
next();
})
.catch(err => console.log(err));
});
mongoConnect(() => {
app.listen(3000);
});
Creating a chat server.
However, when I send a message, it goes into the queue, but then mysql doesn't have data. I think the server is turning on, but I keep getting an error like Socket closed absolutely during opening handshake Help me
consumer.js
`
Consumer: async () => {
try {
const connect = await amqp.connect(amqpURL);
const ch = await connect.createChannel();
const queue = "queue";
await ch.assertQueue(queue, async (message) => {
console.log(message.value.toString());
});
arr.push(JSON.parse(message.value.toString()));
console.log(arr);
if (arr.length == 5) {
try {
const rows = await chatting
.bulkCreate(arr, { hooks: true })
.catch((err) => {
console.log(err);
});
arr.splice(0);
console.log(rows);
return;
} catch (err) {
console.log(err);
}
ch.ack(message);
}
} catch (err) {
console.log(err);
}
},
app.js
`
const express = require("express");
const app = express();
const cors = require("cors");
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const { chatting, sequelize } = require("./models");
const rabbitmq = require("./rabbit");
//const consumer = require("./consumer");
const amqp = require("amqplib");
const amqpURL = "amqp://localhost:5672";
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
sequelize
.sync({ force: false })
.then(() => {
console.log("연결됨");
})
.catch((err) => {
console.log(err);
});
const send = async (message) => {
try {
console.log(message);
const connect = await amqp.connect(amqpURL);
const channel = await connect.createChannel();
const exchange = "exchange";
const queue = "queue";
const routingkey = "sample.routing";
await channel
.assertExchange(exchange, "direct", { durable: true })
.catch((err) => console.log(err));
await channel.assertQueue(queue, { durable: true });
await channel.bindQueue(queue, exchange, routingkey);
await channel.publish(exchange, routingkey, Buffer.from(message));
} catch (err) {
console.log(err);
}
};
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/test", async (req, res) => {
try {
const { idx } = req.body;
const rows = await chatting.findOne({ idx: idx });
if (rows) return res.status(200).json({ result: rows });
} catch (err) {
console.log(err);
}
});
io.on("connection", (socket) => {
console.log("connect");
socket.on("disconnect", () => {
console.log("disconnect");
});
});
io.emit("some event", {
someProperty: "some value",
otherProperty: "other value",
});
io.on("connection", (socket) => {
socket.on("chat message", async (message) => {
try {
await send(JSON.stringify(message));
io.emit("chat message", message);
console.log(message);
} catch (err) {
console.log(err);
}
});
});
server.listen(2022, () => {
console.log("listening on :2022");
});
rabbitmq.Consumer();
`
`
pic
enter image description here
I tried many things and I want to solve
Error: Socket closed abruptly during opening handshake
at Socket.endWhileOpening
this error
I am trying to use 'POST' to create a new movie data with using MongoDB. but when I use 'postman' to post my data it kepts saying like this
{"message":"Operation movies.insertOne() buffering timed out after 10000ms"}
I will post three javascript files please let me know about my problem.
First : index
Second : movie(module)
Third : routes
const router = express.Router();
const Movie = require('./models/movie');
//Fetch all movies
router.get("/movies", async (req, res) => {
try {
const movies = await Movie.find();
res.send(movies)
} catch(err) {
return res.status(500).json({message: err.message});
}
})
// Add movie
router.post("/movies", async (req, res) => {
const movie = new Movie({
title: req.body.title,
director: req.body.director,
year: req.body.year
});
try {
const newMovie = await movie.save();
res.status(201).json({ newMovie });
} catch(err) {
return res.status(500).json({ message: err.message });
}
})
module.exports = router;
//from here is Movie.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MovieSchema = new Schema(
{
title: {type: String, required: true, maxlength: 150},
director: {type: String, required: true, maxlength: 200},
year: {type: Number, required: true}
}
);
//Export model
module.exports = mongoose.model('Movie', MovieSchema);
// from here is routes.js
const express = require('express');
const router = express.Router();
const Movie = require('./models/movie');
//Fetch all movies
router.get("/movies", async (req, res) => {
try {
const movies = await Movie.find();
res.send(movies)
} catch(err) {
return res.status(500).json({message: err.message});
}
})
// Add movie
router.post("/movies", async (req, res) => {
const movie = new Movie({
title: req.body.title,
director: req.body.director,
year: req.body.year
});
try {
const newMovie = await movie.save();
res.status(201).json({ newMovie });
} catch(err) {
return res.status(500).json({ message: err.message });
}
})
enter code here
module.exports = router;
I feel this is so hard to understand lol
Try to refactor your code like this:
router.post("/movies", async (req, res) => {
try {
let newMovie = await Movie.create(req.body);
res.status(201).json(newMovie);
} catch(err) {
return res.status(500).json({ message: err.message });
}
})
In the provided code I don't see you that you are connecting to the database using mongoose.connect for example:
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});
Link for the docs.