I am learning Nodejs, but now I am getting this
error
there is no more code accept this:
let express = require('express')
let mongodb = require('mongodb')
let server = express()
let db
let connectionString = 'mongodb+srv://admin:******#cluster0-1vj27.mongodb.net/TodoApp?retryWrites=true'
mongodb.connect(connectionString, {useNewUrlParser: true}, function(err, client) {
db = client.db("TodoApp")
server.listen(3000)
})
server.use(express.urlencoded({extended: false}))
server.get('/', function(req,res) {
res.send(`....`)
})
server.post('/create-item', function(req, res) {
db.collection('items').insertOne({text: req.body.item}, function() {
res.send("Thank you submitting the form.")
})
})
I am new to node, please help I am stuck.
What should I do now please help
You must use mongodb.MongoClient, not mongodb directly :
const mongodb = require('mongodb');
const mongoClient = mongodb.MongoClient;
// connect
Find an example here : https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
Also, you should check if there is an error before trying to access client :
mongoClient.connect(connectionString, {useNewUrlParser: true}, function(err, client) {
if (err) {
console.error(error);
return;
}
db = client.db("TodoApp")
server.listen(3000)
})
Related
Im trying to insert / Post data in my mongoDb database using exrpess and through Postman, however im at loss in how to perform it. I defined an url being "/api/post" which executes a request of post and asks for now only the "title". When I use postman to create some data, it returns to me as "undefined" with an empty object.
Here is the code:
const {MongoClient} = require('mongodb');
const express = require("express");
const mongoose = require("mongoose")
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
const { schema } = mongoose;
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
app.get("/", (req, res) => {
res.json(result)
})
app.post("/api/post", (req, res) => {
const title = req.body
console.log(title)
res.json({
title
})
})
db.close()
})
})
main().catch(console.error)
Here is the Postman Req.
I would appreciate any feedback an help, thanks!
I'm trying to get data from a collections database in my MongoDB using Node, which I've done successfully. My only problem is how to render the obtained data from the collections and posting it into the express app.
const { MongoClient } = require('mongodb');
const express = require("express");
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close()
})
})
}
main().catch(console.error)
I solved my own problem by just performing an app.get() in the part were it says Mongoclient.connect() and the rest is done by logic, it displays now in the express and in postman as well.
const {MongoClient} = require('mongodb');
const express = require("express");
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
app.get("/", (req, res) => {res.json(result)})
db.close()
})
})
app.listen(4000, function() {
console.log("listening to port 4000)
}
main().catch(console.error)
Here is another way:
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const app = express();
const url = 'mongodb://localhost:27017';
const dbName = 'test';
const port = 3000;
app.listen(port);
// Type this in your browser to see db data: http://localhost:3000/
app.get('/', function(req, res) {
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect(function(err) {
console.log("Connected to server.");
const db = client.db(dbName);
db.collection("books")
.find({})
.toArray(function(err, result) {
if (err) throw err;
client.close();
console.log("Done reading db.");
res.send(JSON.stringify(result));
});
});
});
I am trying to send data through Postman to a REST API made of Node.js and Mongoose
I am getting the following response :
but this does not persist or save to Mongo DB :
I added the following :
mongoose.set("debug", (collectionName, method, query, doc) => {
console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});
so I am also getting this at the console (is session supposed to be null)?:
standups.insertOne {"_id":"5f9e54cea6d454065f0a963b","teamMember":"Mark","project":"Trinity Web Application","workYesterday":"Build out the Models","workToday":"Testing the API Endpoint using Postman","impediment":"None","createdOn":"2020-10-31T22:30:03.000Z","__v":0} { session: null }
I have configured with the following files at my server backend :
api/routes/standup.js
const Standup = require('../../models/standup')
module.exports = function (router) {
// GET: the 12 newest stand-up meeting notes
router.get('/standup', function (req, res) {
})
// POST: Get new meeting note document...
router.post('/standup', async function (req, res) {
let note = new Standup(req.body)
await note.save(function (err, note) {
if (err) {
return res.status(400).json(err)
}
res.status(200).json(note)
})
})
}
api/models/standup.js
const mongoose = require('mongoose')
const standupSchema = new mongoose.Schema({
teamMember: { type: String },
project: { type: String },
workYesterday: { type: String },
workToday: { type: String },
impediment: { type: String },
createdOn: { type: Date, default: Date.now }
}, { bufferCommands: false })
module.exports = mongoose.model('Standup', standupSchema)
app.js
const express = require('express')
const app = express()
const api = require('./api')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cors = require('cors')
const port = process.env.PORT || 8081
app.set('port', port)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(cors())
app.use('/api', api)
app.use(express.static('static'))
app.use(morgan('dev'))
app.use(function (req,res) {
const err = new Error('Not Found')
err.status = 404
res.json(err)
})
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/virtualstandups', {useNewUrlParser: true, bufferCommands: false})
mongoose.set("debug", (collectionName, method, query, doc) => {
console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error: '))
db.once('open', function() {
console.log('Connected to MongoDB')
app.listen(port, function() {
console.log('API Server Listening on port ' + app.get('port') + '!')
})
})
Backend does return original object; however does not persist and sends no error. I am using MongoDB and Node through WSL2.
Ok, my problem was
I installed Mongo DB as a service on windows
I installed mongodb on WSL2 / Ubuntu at a different time ( I forgot I already installed on windows)
Both using the same port 27107
Using Mongo DB Compass, I can only see the Windows MongoDB which yielded no changes; but data was actually getting sent to the WSL2/Ubuntu MongoDB.
Solution :
Uninstall MongoDB on Windows or run MongoDB in only one platform.
I'm new in node.js and mongo db and i have done my code like this in all my routes.
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var ObjectID = mongo.ObjectID;
var collection;
//Connection to mongo db using mongo client
MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function(err, db) {
//connection error or success message
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
throw err;
} else {
console.log("connected to the mongoDB");
}
//index
router.get('/', function(req, res) {
collection = db.collection('category');
collection.find({}).toArray(function(err, category) {
collection = db.collection('subcategory');
collection.find({}).toArray(function(err, subcategory) {
collection = db.collection('product');
collection.find({}).toArray(function(err, product) {
collection = db.collection('banner');
collection.find({status: 'A'}).toArray(function(err, banner) {
console.log(banner);
res.render('home',
{
title : 'Home',
categorys : category,
subcategorys : subcategory,
products : product,
banner : banner
}
);
});
});
});
});
});
});
module.exports = router;
please help me to make a connection in common and access it from all my routes without repeating the connection call. thanks in advance
Here is the draft code to keep the connection outside each request (i.e. connect once) and reuses the database/collection variable.
NodeJS Mongo Driver default connection pool size is 5.
Important: db and categoryCollection variables are kept outside each requests.
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MONGODB_URI = 'mongodb://127.0.0.1:27017/mydb';
var db;
var categoryCollection;
// Initialize connection once
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
categoryCollection = db.collection('category');
app.listen(3000);
console.log('Listening on port 3000');
});
app.get('/', function(req, res) {
categoryCollection.find({}).toArray(function(err, category) {
});
});
You can use Mongoose to connect to MongoDB. With Mongoose you need to connect to the database only once to access it from all the routes. In you app.js add these lines:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test_db', { useNewUrlParser: true }, function (err) {
if (err) throw err;
});
and in your routes you can now access MongoDB without having to write any connection code.
My code as follows. Open localhost/users/,brower return
{"_id":"55519446e063d4c409f93f00","username":"justnode","__v":0}
but when I open mongo shell and input: use student and db.student.find(),I can't find anything. My MongoDB version is 3.0.1 and nodejs version is 0.12.2, OS is Centos 6.4
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/student', function (error) {
if (error) {
console.log(error);
}
});
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: {type: String, unique: true}
});
var UserModel = mongoose.model('UserModel', UserSchema);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
/*
post content as follows
{
"username": "justnode"
}
*/
app.post('/users/create', function (req, res) {
console.log("in /users/create");
var userModelJson = req.body;
var userModel = new UserModel(userModelJson);
userModel.save(function(error) {
if(error) {
console.log(error);
return res.json({msg: "error"});
}
console.log("user created: " + userModel.username);
res.json(userModel);
});
});
/*
open localhost/users/ brower return {"_id":"55519446e063d4c409f93f00","username":"justnode","__v":0}]
but when I open mongo client: db.student.find() i can't find anything
*/
app.get('/users', function (req, res) {
UserModel.find({}, function (err, docs) {
res.json(docs);
});
});
var serverApp = app.listen(80, function () {
console.log('Express server listening on port ' + serverApp.address().port);
});
Change database(student), schema(UserSchema) and model(UserModel)'s name and try it again. My case, after changing the variable's name and restart, it works. (I've no idea why, maybe mongoose or mongo shell has some bug?)