How to Update data from Node.js - node.js

I want to update my data by using id but all the time i am not able to update it. It is even not giving any error and storing null values
router.put('/special/:id', function(req, res) {
User.findByIdAndUpdate(req.params.id, {
$set: {email: req.body.email, password: req.body.password}
},
{
new: true,
useFindAndModify: false
},
function(err, updatedData) {
if(err) {
res.send('Error updating');
} else {
res.json(updatedData);
}
});
});

Try rewriting it using async, and make sure your Mongoose schema is correct as well.
So your mongoose model should be a seperate file called 'userModel.js'.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema ({
email: String,
password: String,
});
let User = module.exports = mongoose.model('User', userSchema);
Then in your app.js.
Have:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const port = 3000;
const bodyParser = require('body-parser');
//Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//connect to db
mongoose.connect('mongodb://localhost:27017/YOUR_DB_NAME_HERE',{useNewUrlParser: true})
let db = mongoose.connection;
//check db connection
db.once('open', function() {
console.log('Connected to ' + db.name)
})
//check for db error
db.on('error', function(err) {
console.log(err);
})
//Starting App (on localhost:3000)
app.listen(port, function() {
console.log('Server started on port ' + port);
});
Note: Once you start the app. In your node console if you are not seeing a message saying 'Connected to {YOUR DB NAME}'. Then either you don't have mongoDB running or you don't have it installed. So first you want to make a new console window and type:
mongod
This should work, and if its already running you should see a message at the bottom saying:
2019-07-19T12:17:37.716+1000 E STORAGE [initandlisten] Failed to set up listener: SocketException: Address already in use
Now once you figure this out. And you've found that your connection to mongoDB is good. You want to redo your PUT route to make an async request as follows.
Note: Before the route, you need to require your model so mongoose can update records for you.
//Requiring your shop model
const User = require('./models/userModel')
app.put('/special/:id', async function(req, res){
const id = req.params.id
//Making a user object to parse to the update function
let updatedUser = {}
updatedUser.email = req.body.email
updatedUser.password = req.body.password
await User.findByIdAndUpdate(id, updatedUser, function(err, updatedData){
if(err){
console.log(err)
}
else {
console.log(updatedData)
//res.redirect or res.send whatever you want to do
}
})
})

Related

Node Express Mongo API return empty result set

I'm going to develop API using Node Express & Mongo.I have manually entered data to mongo db like below and when i try to get data from the db it shows me empty in postman.Here i have paste my project code for easy to figure out.
In the controller returned empty results.
my project structure looks like this
db.config.json
module.exports = {
//url: "mongodb://localhost:27017/TestDb"
url: "mongodb://localhost:27017/Users"
};
server.js
const express = require("express");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to Shopping List." });
});
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
const db = require("./app/models");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
index.js
const dbConfig = require("../config/db.config.js");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.users = require("./user.model.js")(mongoose);
console.log(db.url);
module.exports = db;
user.contoller.js
const db = require("../models");
const User = db.users;
// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
User.find({ isAdmin: false })
.then(data => {
console.log("datanew"+data); // <-- Empty returns here.. []
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving user."
});
});
};
user.model.js
module.exports = mongoose => {
var schema = mongoose.Schema(
{
firstName: String,
lastName: String,
password: String,
email:String,
isAdmin:Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("user", schema);
return User;
};
user.route.js
module.exports = app => {
const users = require("../controllers/user.controller.js");
var router = require("express").Router();
// Retrieve all Tutorials
router.get("/", users.findAll);
app.use('/api/users', router);
};
It appears you manually created your MongoDB collection. Users must be in small letters so from the MongoDB interface, change Users => users and you'll be set.
Also your DB connection uri should be:
module.exports = {
url: "mongodb://localhost:27017/TestDb"
};
TestDB is the database while users is the collection. Your uri must point to a db that your code will query collections in.
Your User Model
This is just a slight change but you want to keep your code consistent. User should all be in capitalize form. MongoDB is smart to user plural and small caps automatically in the db.
module.exports = mongoose => {
var schema = mongoose.Schema(
{
firstName: String,
lastName: String,
password: String,
email:String,
isAdmin:Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("User", schema);
return User;
};
// Actually you can remove
index.js
db.config.js files
// *********
add in server.js
const express = require('express')
const mongoose = require('monggose')
const app = express()
mongoose.connect('mongodb://localhost/TestDb');

Mongoose unable to save or persist to database with a POST Request; gives no error

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.

mongoose required true req.body.name {}

If I set required to false, it will successfully create an object in the MongoDB database with one id. I suffer confusion sometimes, check my profile if you want. I think it's a little thing. If you need more info, just comment.
app.js
var express = require('express');
var bodyParser = require('body-parser');
var product = require('./routes/product'); // Imports routes for the products
var app = express();
var mongoose = require('mongoose'); // Set up mongoose connection
var dev_db_url = 'mongodb://localhost/Product';
var mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/products', product);
var port = 3002;
app.listen(port, () => {
console.log('Server is up on port numbner ' + port);
});
model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: {type: String, required: true, max: 100},
price: {type: Number, required: true},
});
module.exports = mongoose.model('Product', ProductSchema);
controller.js
var Product = require('../models/product');
//Simple version, without validation or sanitation
exports.test = function (req, res) {
res.send('Greetings from the Test controller!');
};
exports.product_create = function (req, res, next) {
var product = new Product(
{
name: req.body.name,
bags: req.body.bags
}
);
console.log(JSON.stringify(req.body))
product.save(function (err) {
if (err) {
return next(err);
}
res.send('Bags Created successfully')
})
};
router.js
var express = require('express');
var router = express.Router();
// Require the controllers WHICH WE DID NOT CREATE YET!!
var product_controller = require('../controllers/product');
// a simple test url to check that all of our files are communicating correctly.
router.get('/test', product_controller.test);
router.post('/create', product_controller.product_create);
module.exports = router;
HTTP POST: http://localhost:3002/products/create?name=Jorge&price=20
ValidationError: Product validation failed: name: Path name is
required
Can you help?
Thanks!
💡 The reason why it's error, because your req.body.name is empty or null. Why it's null or empty or undefined? Because you're not add your data in your body, when you send create request.
You can see your Endpoint:
HTTP POST: http://localhost:3002/products/create?name=Jorge&price=20
It's not about req.body, it's a req.params. So you can use req.params.name and req.params.price.
🕵️‍♂️ So, If you're passing your data using parameres, your code will looks like this:
exports.product_create = function (req, res, next) {
var product = new Product(
{
name: req.params.name,
price: req.params.price
}
);
console.log(req.params);
product.save(function (err) {
if (err) {
return next(err);
}
res.send('Bags Created successfully')
})
};
If you want to use req.body, than add your json object tobody if you're using Postman.
🕵️‍♂️ You can see the image below: An example using postman to passing your data into body, before you send create request to your backend.
So, If You're passing your data from body, than your code will looks like this:
exports.product_create = function (req, res, next) {
var product = new Product(
{
name: req.body.name,
price: req.body.price
}
);
console.log(req.body);
product.save(function (err) {
if (err) {
return next(err);
}
res.send('Bags Created successfully')
})
};
I hope it's can help you.

Mongoose doesn't save documents to my database locally

My problem is simple as i guess.
i can run mongoose to save documents to my DB on mlab.
also can see the saved data via postman on get requests.
but when i use local mongodb instead of mlab then try to show the db collections on my terminal by running "mongo" then select the same db to which mongoose is connected
it shows me an empty db.
i try again to send post request with new data.. and the result is same, positive on postman and mlab, but when connect to local mongodb and post new data.. there is nothing there at all. the only way i can insert data to my shell is through the command insert().
Any idea why is this happening?
Thank you in advance.
app.js
var express = require("express");
var app = express();
var port = 8080;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/test",{ useNewUrlParser: true });
// Model & Schema
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
// Routes
app.get('/users', (req, res) => {
User.find({}, (err, user) => {
if (err) throw err;
console.log(user)
res.send(user)
})
})
app.post("/addname", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
Here when i use mlab:
BUT when using local machine..:
try like below in add api
app.post("/addname", (req, res) => {
req.body = JSON.parse(JSON.stringify(req.body)); //This line is Optional, some time req.body is in json buffer form so we are converting to pure json
User(req.body).save().then(item => {
console.log("DB Item saved --->", item);
res.status(200).send("item saved to database");
}).catch(err => {
res.status(400).send("unable to save to database");
});
});
dont forget that req.body must contain firstName, lastName
After your Question update regarding the listing of Collection(Schema) Documents
Your are trying
db.test.find()
which will not work because Your Schema name is User and will save as users since mongodb prefer Plural collection names because it consists of more than One Documents
You must try
db.users.find() in your mongo shell
It will return all documents of User Collections.
If you want specific collection name(Schema name) then you have to create schema as below
// Model & Schema
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
}, { collection: 'User' });
var User = mongoose.model("User", nameSchema);
In mongo shell you must try like
db.User.find();
For listing all collection in mongo shell you must try like below
db.getCollectionNames()

When I use mongoose & connect MongoDB, I can insert and get data. But unable to find data using MongoClient

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?)

Resources