Mongoose doesn't save documents to my database locally - node.js

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

Related

How to set DB name and Collection name in Mongoose?

I'm building a small program that connects to MongoDB-Atlas.
I created a connection, a Schema, a Model and created a document.
but somehow my DB name is "test" and Collection name is "users" without me defined it in the code or in Atlas, is that the default names? and how to create/rename a DB and a collection.
the code :
user.js
const mongoose = require('mongoose');
const SchemaObj = mongoose.Schema;
const userSchema = new SchemaObj({
name : {
type:String,
require:true
},
email : {
type:String,
require:true
},
password: {
type:String,
require:true
}
});
mongoose.model('User',userSchema);
app.js
const express = require('express');
const app = express();
const rout = express.Router();
const PORT = 8888;
const {connectionString} = require('./Keys');
const mongoose = require('mongoose');
app.use(express.json());
app.use(require('./routes/auth'));
app.get('/',(req,res)=>{
console.log('succesfully connected');
res.send('im in!');
});
let server = app.listen(PORT,'0.0.0.0',()=>{
let FuncPort = server.address().port
let host = server.address().address
console.log("Example app listening at http://%s:%s", host, FuncPort)
});
const client = mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected',()=>{
console.log('connected to mongodb oh hell yea');
});
mongoose.connection.on('error',()=>{
console.log('error connecting to mongodb oh hell yea');
});
auth.js
const mongoose = require('mongoose');
const express = require('express');
const route = express.Router();
require('../moduls/User');
const user = mongoose.model("User");
rout.post('/sign',(req,res)=>{
const {name,password,email} = req.body;
if(name && password && email) {
console.log('you god damn right!');
res.json("you god damn right in response");
} else {
console.log('you are god damn wrong stupid idiot!');
res.status(422);
res.json("you are god damn wrong you stupid idiot in response");
}
user.findOne({email:email}).then((resolve,reject)=>{
if(resolve)
return res.status(422).json("user already exist yo");
const newUser = new user({ name, email, password });
newUser.save().then(() => {
res.json('saved user!!!!');
}).catch(err => {
console.log("there was a problem saving the user")});
}).catch(err => {
console.log(err);
})
});
module.exports = route;
By the way, what is the difference between mongoose and MongoDB libraries?
For naming your mongodb database, you should place it in your connection string, like:
mongoose.connect('mongodb://localhost/myDatabaseName');
For naming your collection or disabling pluralization, you can find the answer here:
What are Mongoose (Nodejs) pluralization rules?
var schemaObj = new mongoose.Schema(
{
fields:Schema.Type
}, { collection: 'collection_name'});
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. Similar to Sequelize (ORM) but for documents (NoSQL).
MONGODB_URI = mongodb+srv://name:#next.txdcl.mongodb.net/(ADD NAME DB)?retryWrites=true&w=majority
You can just add name what you want ( ADD NAME ) and delete test db and reloa
Approach 1
const url = "mongodb://127.0.0.1:27017/DatabaseName"
mongoose.connect(url).then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
Approach 2
const url = "mongodb://127.0.0.1:27017"
mongoose.connect(url,{
dbName: 'DatabaseName',
}).then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
This is how I change my DB name
Before
mongodb+srv://username:<password>#clustername.abc.mongodb.net/?retryWrites=true&w=majority
after you get your API key you can add 1 more path (/) before the query (?) and that path will be your DB name automatically
the example: I add my DB name as
my-new-db-name
after
mongodb+srv://username:<password>#clustername.abc.mongodb.net/my-new-db-name?retryWrites=true&w=majority

How to Update data from 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
}
})
})

How can i get a particular field corresponding to a question from mongodb in nodejs

I am trying to create a rest api that fetches the answer corresponding to the question from mongo db. However, i am new to mongo so is there any way that I can give response to the user based on the specific question from the database.
Here is my code:
var express = require("express");
var app = express();
var port = 3000;
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/questionandanswer");
var nameSchema = new mongoose.Schema({
question: String,
answer: String
});
var User = mongoose.model("User", nameSchema);
app.get("/getanswer",function (req, res) {
User.find({}).then(eachOne =>{
res.json(eachOne);
})
});
app.post("/addquestion", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("question saved to database");
})
.catch(err => {
res.status(400).send("Unable to save to database");
});
});
var port=process.env.port || 5005;
app.listen(port, () => {
console.log("Server listening on port " + port);
});
Here is my database image file:
mongodb database
My code return me all the stored answers however i only want answers to specific question.
You can use specific Id or Question
User.find({"question" : "how are you"}).then(eachOne =>{
res.json(eachOne);
})
Or
User.find({"_id" : ObjectId("5c73....7f")}).then(eachOne =>{
res.json(eachOne);
})

Mongoose or MongoDB for Schema definition?

Mongoose is used to define a schema. right?
Is it is possible to create a schema with mongoDB through mongo Shell ? like
eg: name:String
MongoDB doesn't support schema. It's a schemaless document based DB.
Mongoose is an ODM(Object Document Mapper) that helps to interact with MongoDB via schema, plus it also support validations & hooks.
Basically mongodb is schema less database we cant able to create schema directly in mongodb. Using mongoose we can able to create a schema. Simple CRUD operation using mongoose, for more info ref this link
package.json
{
"name": "product-api",
"main": "server.js",
"dependencies": {
"express": "~4.0.0",
"body-parser": "~1.0.1",
"cors": "2.8.1",
"mongoose": "~3.6.13"
}
}
product.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
title: String,
price: Number,
instock : Boolean,
photo : String ,
});
module.exports = mongoose.model('Product', ProductSchema);
// module.exports = mongoose.model('Product', ProductSchema,'optiponally pass schema name ');
server.js
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var mongoose = require('mongoose');
var product = require('./product');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();
mongoose.connect('mongodb://localhost:27017/products');
// Middle Route
router.use(function (req, res, next) {
// do logging
// do authentication
console.log('Logging of request will be done here');
next(); // make sure we go to the next routes and don't stop here
});
router.route('/products').post(function (req, res) {
console.log("in add");
var p = new product();
p.title = req.body.title;
p.price = req.body.price;
p.instock = req.body.instock;
p.photo = req.body.photo;
p.save(function (err) {
if (err) {
res.send(err);
}
console.log("added");
res.send({ message: 'Product Created !' })
})
});
router.route('/products').get(function (req, res) {
product.find(function (err, products) {
if (err) {
res.send(err);
}
res.send(products);
});
});
router.route('/products/:product_id').get(function (req, res) {
product.findById(req.params.product_id, function (err, prod) {
if (err)
res.send(err);
res.json(prod);
});
});
router.route('/products/:product_id').put(function (req, res) {
product.findById(req.params.product_id, function (err, prod) {
if (err) {
res.send(err);
}
prod.title = req.body.title;
prod.price = req.body.price;
prod.instock = req.body.instock;
prod.photo = req.body.photo;
prod.save(function (err) {
if (err)
res.send(err);
res.json({ message: 'Product updated!' });
});
});
});
router.route('/products/:product_id').delete(function (req, res) {
product.remove({ _id: req.param.product_id }, function (err, prod) {
if (err) {
res.send(err);
}
res.json({ message: 'Successfully deleted' });
})
});
app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('REST API is runnning at ' + port);
Mongoose helps to interact with MongoDB in terms of Object/Model so that programmer doesn't need to understand the remember the statements of MongoDB.
Also, Mongoose provides lot of methods of CRUD Operations to better understanding of DB Operations.
You can check examples here
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose
http://mongoosejs.com/docs/
Mongoose has its benefits of validation and schema configurations but it has its cons of latency and some problems with high/mid scale applications.
it's always the best thing IMHO, to use the native mongodb package.
regarding schema, you can create your own "schema" as a json file and write ur own validations for mandatory or valid attributes.
it's faster, with no third party packages and more reliable.

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