Why model.find() in mongoose is running before creating the collection? - node.js

I have this task for creating a database with mongoose and do some CRUD operations:
First I created my server.js file for creating a server and connecting a database to the server
My problem is when I run my app for the first time the person.find() result is always empty!!
server.js:
const express = require('express');
const mongoose = require('mongoose');
const personRoute = require('./routes/personRoute')
const app = express();
app.use(express.json());
//Connecting the database to the server
mongoose.connect('mongodb+srv://admin:123456#checkpoint.scbz2.mongodb.net/Checkpoint?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
},
err => {
if(err) throw err
else console.log('Database is connected')
}
);
//Using routes with express Router
app.use(personRoute)
//Creating server on port 5000
app.listen(5000 , err => {
if(err) console.log(err)
else console.log('Server is running on port 5000')
})
personSchema.js:
const mongoose = require('mongoose');
const { Schema } = mongoose;
//Creating a person schema
const personSchema = new Schema({
name : {type : String, required : true},
age : Number,
favoriteFood : [String]
});
//Exporting the person schema
const person = mongoose.model('person', personSchema);
module.exports = person;
personRoute:
const express = require('express');
const router = express.Router()
const person = require('../model/personSchema');
let arrayOfPeople = require('../arrayOfPeople');
//
let exemple = new person({
name : "Mohamed", age : 26, favoriteFood : ['pasta', 'mloukhia', 'jelbena']
});
exemple.save((err,exemple) => {
if (err) return handleError(err);
else console.log('exemple created and saved: ', exemple);
});
//
person.create(arrayOfPeople,(err, data) => {
if (err) return handleError(err);
else console.log('collection created :', data)
})
//
person.find({name : "Mohamed"}, (err, document) => {
if (err) return handleError(err);
else console.log('Find person by name :', document)
});
module.exports = router;
The problem is in personRoute.js because when I run my app I always get the person.find() result empty actually it always runs before saving the exemple/creating the collection here's an image of my problem:
Image problem
Any help will be always appreciated :)

Related

Mongoose is returning empty array while fetching data from MongoDb Atlas. Why?

App.js file->Connection is established successfully, but in find() callback,data is empty[]
const express = require('express');
const mongoose = require('mongoose');
const Users = require('./users');
const app = express();
mongoose.connect("mongodb+srv://sanjeev:**pass**#cluster0.ckywrym.mongodb.net?retryWrites=true&w=majority/sanjeevDb",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log("connection established successfully"));
Within find callback I am getting empty array in data
Users.find({}, (error, data) => {
if (error)
console.log("Error: ", error);
console.log(data)
});
users.js - defining the schema as same on mongoDb Atlas
const mongoose = require('mongoose');
let userSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
email: String,
country: String
});
module.exports= mongoose.model('userCollect', userSchema);
enter image description here
you are logging data even when there is error. do this
Users.find({}, (err, data) => {
if (err){
console.log(err);
} else {
console.log(data);
})
or
//with async (recommended)
try {
const users = await Users.find({});
console.log(users);
} catch (err) {
console.log(err);
}

API for making query searches not working

I'm trying to fetch all records from MongoDB starting with the Alphabet S but every time I try doing so, it returns nothing but []. I'm using the Params tab on Postman to do this.
The code that I have written is below as well as a snip from Postman to make the question more understandable. I'm pretty sure that the API I have written to perform this has something wrong with it.
The Model file
const mongoose = require('mongoose');
const entry = new mongoose.Schema({
name : {
type : String,
},
collegeName : {
type : String,
},
location : {
type : String,
}
});
const enter = mongoose.model("Student", entry);
module.exports = enter;
index.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongo = require('mongodb');
const dataModel = require('./model/model');
const MongoClient = mongo.MongoClient;
const uri = "mongodb+srv://coolhack069:XzC6N7dOyUeQl8M9#cluster0.kz6v9.mongodb.net/assignment?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
app.use(express.json());
app.use(bodyParser.json());
const port = 3001;
app.get('/api/get', (req, res) => {
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = {};
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
});
})
});
app.get('/api/getStudentDetails', (req, res) => { //The API I have written to query through the Database
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = new dataModel({
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
})
});
app.post('/api/add', (req, res) => { //To add Data
const name = req.body.name;
const collegeName = req.body.collegeName;
const location = req.body.location;
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const storeData = new dataModel({
name : name,
collegeName : collegeName,
location : location
});
console.log(storeData);
collection.insertOne(storeData, function(err, result) {
res.json({
result : "Success"
});
console.log(err);
client.close();
});
})
});
app.listen(port, () => {
console.log(`Application running at http://localhost:${port}`)
})
The Screenshot from Postman
Your find condition is not correct:
const fetchedData = new dataModel({ // ???
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
??? - I guest your meaning is const fetchedData = { name: req.params.name}; - Find every document which have name is req.params.name (S - in your case). But there is no document has name is S in your collection, then it returns [].
If you want to find the documents with S as the first character of their name, you can use Regex syntax:
const query = {
name : new RegExp('^' + req.params.name, 'i'), // i - case insensitive, => /^S/i
};
collection.find(query).toArray(function(err, result) {
res.send(result);
client.close();
})

is there any solution to error in nodejs " Cast to Number failed for value "undefined" at path "

I have a little problem to understand that how to solve this error.i am just a beginner to nodejs and mongodb/mongoose.I am creating a component in reactjs to update any particular documents using its user_id which i am passing a params in routes.
there is the code:
const express = require('express');
const mongoose = require('mongoose');
const mongodb = require('mongodb')
const user = require('../schema');
const router = express.Router();
router.get('/:id', function (req, res) {
const userid = {
userid: (req.params.id || '')
}
console.log('getting to be updated data');
user.db1.findOne(userid, function (err, data) {
if (err) throw err
res.send(data)
console.log(data)
});
});
module.exports = router
//here is the user model:
const userSchema = new mongoose.Schema({
userid:{type:String},
fullname:{type:String},
phone:{type:Number},
email:{type:String},
})
const skillSchema = new mongoose.Schema({
userid:{type:Number},
skills:{type:String},
})
const users = mongoose.model('users',userSchema);
const skills = mongoose.model('skills',skillSchema);
module.exports ={
db1 : users,
db2 : skills
}
I guess you haven't specified in the find.one () function by which parameter it will search. Try it by typing your own column name instead of id.
user.db1.findOne({ id: userid } ,function(err, data){
if (err) throw err
res.send(data)
console.log(data)
});
Or you can change your function and use findById().
user.db1.findById(userid, ,function(err, data){
if (err) throw err
res.send(data)
console.log(data)
});

Can't send data to MongoDB from NodeJs

I'm really new to NodeJs and MongoDB or web development in general. I'm following a tutorial on how to make a registration system that was posted about 2 years ago. With these codes below, he was able to send a post request test using postman and his data was saved into MongoDB, however, when I try to send a post request on postman, it keeps loading at "sending request" and data was never saved to mongoDB...I'm not sure if nodejs has changed syntax or if i'm doing something wrong... please help!!
this is the code for user.controller.js
const mongoose = require('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) => {
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.save((err, doc) => {
if (!err)
res.send(doc);
else {
if (err.code == 11000)
res.status(422).send(['Duplicate email adrress found.']);
else
return next(err);
}
});
this is the code for user.model.js:
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
var userSchema = new mongoose.Schema({
fullName: {
type: String
},
email: {
type: String
},
password: {
type: String
},
saltSecret: String
});
// Events
userSchema.pre('save', function (next) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(this.password, salt, (err, hash) => {
this.password = hash;
this.saltSecret = salt;
next();
});
});
});
mongoose.model('User', userSchema);
this is the code for server(app.js)
const MongoClient = require('mongodb').MongoClient;
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
console.log(`MONGODB CONNECTION SUCCEEDED`);
client.close();
});
require('./user.model');
In controller you have mongoose to write data to mongo but in your server file you are connecting to mongodb using native mongo driver. Hence, it won't work. Either both places you need to have mongodb native driver or mongoose.
Use below code where I have modified the server start file to use mongoose.
const mongoose = require('mongoose'),
const m_url = 'mongodb://127.0.0.1:27017/',
db_name = 'test', // use your db name
m_options = {
'auto_reconnect': true,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
mongoose.connect(m_url + db_name, m_options, function (err) {
if (err) {
console.log('Mongo Error ' + err);
} else {
status.mongo = 'Running'
console.log('MongoDB Connection Established');
}
});
// import/require user controller.

data is not insert in mongodb

I am beginner of nodejs and mongodb. I am inserting data to collection using mongoose ORM and model but not insert. Validation is working correct but data is not insert after filling complete data. I have not create collection in database manually. should I create collection manually in mongodb or create automatically when inserting document.
productsController
var mongoose = require('mongoose');
var db = require('../config/db_config');
var Product = require('../models/product');
//var Product = mongoose.model('Products');
var productController = {};
productController.add = function(req, res) {
var params = req.body;
if(!params) {
res.status(400).send({message: "Data can not be empty"});
}
var productData = new Product({
product_name : params.product_name,
price : params.price,
category : params.category
});
console.log(productData);
productData.save(function(err, product) {
if (err){
res.status(400).send({message:'Unable to save data! ' + err});
}else{
res.status(200).send({message:'Data has been saved! ' + product });
}
});
};
module.exports = productController;
Models code is here
var mongoose = require('mongoose');
var db = require('../config/db_config');
var Schema = mongoose.Schema;
var productSchema = new Schema({
product_name: { type: String, required: 'Product name cannot be left blank.' },
price: { type: String, required: 'Product price cannot be left blank.'},
category: { type: String , required: 'Product category cannot be left blank'},
updated_at : {type: Date, default: Date.now}
});
module.exports = mongoose.model('Products', productSchema);
routes file code is here:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Product = require('../models/product.js');
var productsController = require('../controllers/productsController');
router.post('/add',productsController.add);
module.exports = router;
DB config file
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var db = mongoose.createConnection('mongodb://localhost:27017/nodeweb', function(err,db){
if(err){
throw err;
console.log(err);
} else {
console.log('Successfully connected to database!');
}
});
module.exports = db;
I have insert controller, model and routes file code.
Please correct your method -
Controller function
exports.add = function(req, res) {
var new_product = new Products(req.body);
// you have define Products not Product
console.log(new_product);
new_product.save(function(err, product) {
console.log('add data');
if (err){
res.send(err);
}else{
res.json(product);
}
});
};
and for good practice in node js - i think you can start with express-app-generator
This Helps to make simple routing, with generic responses and in-built express middlewares with loggers.
I have resolved problem. database connection work with connect method.
mongoose.connect('mongodb://localhost:27017/nodeweb', {useMongoClient: true}, function(err,db){
if(err){
throw err;
console.log(err);
} else {
console.log('Successfully connected to database!');
}
});

Resources