Nodejs: not getting any data while fetching data from MongoDB? - node.js

I am trying to fetch data from MongoDB by a field name - pubdate, but data is not showing neither I am getting any error!
I have field in the collection - _id, article, headline, pubdate all are String type except _id which is Objectid.
When I tried this query in Mongo query browser like - compass and studio 3t I got data -
{ pubdate: { '$gte': '2022-12-01', '$lte': '2022-12-31' } }
I am using postman to fetch data, in raw option sending POST request in JSON form.
{"fdate":"2022-12-31","tdate":"2022-12-31"}
const express = require("express");
const app = express();
const port = 3005;
const mongoose = require("mongoose");
// Connect to MongoDB using Mongoose
const url =
"mongodb://localhost:2701/db";
mongoose.connect(url, { useUnifiedTopology: true, useNewUrlParser: true });
const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));
// Define the Article schema
const articleSchema = new mongoose.Schema({
headline: String,
fulltext: String,
pubdate: String,
article_type: String,
});
const Article = mongoose.model("collectioname", articleSchema);
// Route for retrieving articles based on fromdate and todate
app.post("/articles2", (req, res) => {
let _fDate = req.body.fdate;
let _tDate = req.body.tdate;
Article.find({
pubdate: { $gte: _fDate, $lte: _tDate },
}).exec((err, articles) => {
if (err) {
console.error(err);
res.status(500).send("Error retrieving articles");
return;
}
res.send(articles);
});
});
// Start the server
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
How Will I pass the value in Postman to get the record, I am clueless as of now?
I tried map function too but no output-
let _articles = articles.map((x) => x.articleid); res.send(_articles);

Your issue is caused by Mongoose, by default, lowercasing and pluralizing the name that you pass when creating the model to determine the name of the collection it will use for the model.
In other words, when you use mongoose.model('User', UserSchema), Mongoose will take the name (User) and lowercase and pluralize it, so the collection becomes users.
If you want Mongoose to use an existing collection, or if you want to have full control of the collection name, you need to use the collection option in your schema:
const articleSchema = new mongoose.Schema({
headline: String,
fulltext: String,
pubdate: String,
article_type: String,
}, {
collection : 'article_fulltext' // the collection to use for this schema
});
const Article = mongoose.model("Article", articleSchema);
Without this option, and assume that you used article_fulltext as the model name, Mongoose would have used a collection named article_fulltexts.

Can you try logging what articles return in exec callback?
One possible issue could be that variables _fDate and _tDate are not seen as Dates by mongoose.So try wrapping them with new Date?
Article.find({
pubdate: { $gte: new Date(_fDate), $lte: new Date(_tDate) },
})

Related

How to fetch all data only from mongoose with Nodejs

I am not able to fetch all the data from mongoose. When I tried to fetch data it create new collection name(signins) with empty, but singin collection already exists.
I don't understand what I am doing wrong here
Index.js File
const express = require("express");
const app = express();
const mongoose = require("mongoose");
mongoose
.connect("mongodb://0.0.0.0:27017/signin")
.then(() => console.log("MongoDB Connected"))
.catch((err) => console.log(err));
const User = require("./models/signin");
app.use("/", (req, res) => {
User.find({}, (err, data) => {
if (err) throw new err();
return res.json(data);
});
});
app.listen(5500, () => console.log("Port Started on 5500"));
signin
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const loginSign = new Schema({
email: { type: String, required: true },
password: { type: String, required: true },
date: { type: Date, default: Date.now },
});
module.exports = Users = mongoose.model("signin", loginSign);
Mongoose will automatically "pluralize" the name of your collection from your model name.
So mongoose.model("signin", loginSign) is creating a collection named "signins".
From the documentation: https://mongoosejs.com/docs/models.html#compiling
The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name.
Providing a third argument will use a collection name you specify, instead of the one mongoose creates. So in your case you could:
mongoose.model("signin", loginSign, "signin");
That said, having plural collection names is the standard, and encouraged.

Why am I not able query ( User.findOne() ) my mongoDB after setting up a Schema?

I can't seem to query my MongoDB after setting up the MongoDB schema. I don't understand where I am going wrong with my MongoDB schema, any help is appreciated!
I WAS earlier successful in querying my mongodb before creating a schema, using queries like this:
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);
const result = await client.db("inride_adverts").collection("adverts").findOne({OrgEmail: OrgEmailToSignIn});
However, according to a YouTube tutorial am following (10:40 mins), after setting up a mongodb schema, I am NOT successful in using the following query to interact with my mongodb:
User.findOne( {OrgEmail: signUpEmail} ).exec();
Find below my simple User Schema:
./models/User.js
import { mongoose} from 'mongoose';
const UserSchema = new mongoose.Schema({
OrgName: {
type: String,
required: true
},
OrgEmail: {
type: String,
required: true
},
OrgPwd: {
type: String,
required: true
}
}, { collection: 'adverts' });
export const User = mongoose.model('User', UserSchema);
Also, find below my server.js file
./server.js
import express from 'express';
import { User } from './models/User.js';
import mongodb from 'mongodb';
import { mongoose} from 'mongoose';
mongoose.connect(db, { useNewUrlParser: true })
mongoose.connect(db, { useNewUrlParser: true })
.then( () => console.log("MongoDB Connected..." ))
.catch(error => console.log(err))
app.route('/advertiserRegister')
.post( async (req, res) => {
let formData = req.body;
let signUpName = formData.signUpName;
let signUpEmail = formData.signUpEmail;
let signUpPwd = formData.signUpPwd;
console.log("signUpName: " +signUpName);
console.log("signUpEmail: " +signUpEmail);
console.log("signUpPwd: " +signUpPwd);
if(signUpPwd !== signUpPwdConfirm){
console.log("Passwords arent EQUAL!");
return 0;
} else {
try{
console.log("signUpEmail>>> : " + signUpEmail );
// Validation passed!
const testing = await User.findOne( {OrgEmail: signUpEmail} ).exec();
console.log("testing >>> : " ,testing );
res.redirect('/advertiserLogin')
} catch {
//console.error('error', code);
console.log("Error logging in ");
res.redirect('/advertiserRegister')
};
}
});
The server.js file yields:
MongoDB Connected...
signUpName: Merc Enterprise LTD
signUpEmail: hundredcent.a#gmail.com
signUpPwd: 555
signUpEmail>>> : hundredcent.a#gmail.com
testing >>> : **null**
Error logging in
Turns out that the reason I was NOT able to query my collection was due to the fact that I was unknowingly querying the incorrect collection being: adverts under the incorrect database being: inride_adverts.
I came to understand and realise that In my ./models/User.js, the mongoose.model('User', UserSchema); code creates a new database in Atlas MongoDB called test and creates a totally new collection called User.
Having understood this, I am able to populate and query this collection successfully!

How does mongoose know what collection I am accessing?

I'm having a trouble grasping a concept in Mongoose.
I'm using MongoDB atlas, got a cluster , a database and 2 collections.
users, characters.
Through a guide I've learned that a good way to write your stuff is to have a model (I use the naming schema) as a file, importing it into your Database module/class
and using it there to perform a query...
const mongoose = require("mongoose");
const process = require("./config.env");
db = () => {
return mongoose
.connect(process.env.URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
})
.then((response) => {
console.log(`Connected to Databse : ${response.connection.host}`);
})
.catch((err) => {
console.log("DB_ERROR:", err);
process.exit(1);
});
};
module.exports = db;
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
});
const User = mongoose.model("User", UserSchema);
module.exports = User;
const User = require("../schemas/User");
const db = require("../config/db");
class Database {
constructor(db, collection) {
this.db = db;
this.collection = collection;
this.User = User;
}
connect() {
return db();
}
}
module.exports = Database;
one file to handle the db connection..another file as the User schema and a third file to handle every function i might use globally...
One thing I cannot wrap my mind around is
how is the findOne() function able to locate the collection I am using without me telling it what collection i want it to search in?
is it somehow translating the
const User = mongoose.model("User", UserSchema);
line and searching for "users" as well? I just can't understand the magic behind this...
what if I want to search specifically in the characters collection...?
Mongoose uses the model name, as passed when it was created: mongoose.model("User", UserSchema), converted to lower case and with an 's' appended.
For the model User it uses the collection users by default. You can change this by explicitly specifying the collection name in the schema.

Beginner Issue with Mongoose and MongoDB

I'm new to Node, along with Mongoose and MongoDB. I'm trying to test inserting data into one of the collections in a database on MongoDB Atlas. However, the code somehow inserts the data into the wrong database. I intend to insert data into the 'test' collection in the 'quizzard' database. However, a new collection called 'tests' was created within quizzard where the data was placed. When I tried it again, it started inserting data into another database called 'test' and created a collection called 'tests', where the data is still being placed.
var link = "mongodb+srv://<user>:<password>#quizzard-dp0b2.mongodb.net/test?retryWrites=true&w=majority";
// changed to <user> and <password> for privacy reasons
mongoose.connect(link, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('Connected');
});
const Schema = mongoose.Schema;
const TestSchema = new Schema({
_id: Number,
data: String
});
//TestSchema.set('database', 'test');
//TestSchema.set('collection', 'test');
const Test = mongoose.model('Test', TestSchema);
const data = {
_id: 11,
data: "why???"
};
const newTest = new Test(data);
newTest.save((error) => {
if(error){
console.log("An error has occured");
} else {
console.log("Action performed");
}
});
You need to change the link; after the first slash, you choose which DB you want to use.
Examples
// DB NAME youinsertinheredbname
var link = "mongodb+srv://<user>:<password>#quizzard-dp0b2.mongodb.net/youinsertinheredbname?retryWrites=true&w=majority";
// DB NAME stackoverflow
var link = "mongodb+srv://<user>:<password>#quizzard-dp0b2.mongodb.net/stackoverflow?retryWrites=true&w=majority";

How to connect to specific database with Mongoose and node?

I'm learning how to use Mongoose and there's something I don't understand - how can I connect to specific database and collection in my cluster?
I have 5 different databases and each database have few different collections
When I was using pure Mongo client - the way the show it in official documentation, I connected like that:
const MongoClient = require('mongodb').MongoClient;
const uri = process.env.mongo_connection_string;
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("database_name").collection("collection_name");
// Do some work here in the selected database and the selected collection
client.close();
});
Now I want to use Mongoose to practice. So in my app.js to establish the connection I do:
mongoose.connect(process.env.mongo_connection_string , {useNewUrlParser: true})
.then( () => console.log("Connection established"))
.catch(err => console.log(err))
Then I have created a schema for one of the objects I want to store in the database.
const mongoose = require('mongoose')
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
}
})
const User = mongoose.model('User', UserSchema)
module.exports = User
How do I associate this model with the database and the collection I need?
To connect to a specific database you can add the name in the options like this:
mongoose
.connect(db_url, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'MyDatabaseName',
})
.then(() => {
console.log('Connected to the Database.');
})
.catch(err => console.error(err));
Please specify the database name in URI like link (or)
Please get the default client object with mongo URI then get the required database and collection objects.

Resources