Getting error in nodejs when querying mongodb data? - javascript

I am getting error in nodejs console (see screenshot for more clarification).
In matches.js :
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const matchSchema = new Schema({
match_id:{
type:Number; <---- line 8
required:true;
},
season:{
type:Number;
required:true;
}
.....
.....
});
const matches = mongoose.model('matches', matchSchema);
module.exports = matches;
// Get matches
module.exports.getmatches = (callback, limit) => {
matches.find(callback).limit(limit);
}
In app.js :
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
matches = require('./models/matches');
mongoose.connection.openUri('mongodb://localhost:27017/IPL');
const db = mongoose.connection;
app.get('/home', (req, res) => {
matches.getmatches((err, match) => {
if(err){
throw err;
}
res.json(matches);
});
});
app.listen('5000');
console.log('Running on port 5000....')
I have made model folder which contains matches.js I am trying to access data from mongodb and when to display it as JSON data on API endpoint i.e localhost://5000/home

This is a basic JavaScript Object declaration error. A JSON Object should look like this,
{
match_id: {
type: Number, //see the comma there?
required: true
}
}
Instead of using ,, you have used ; which will throw a syntax error. use this instead,
const matchSchema = new Schema({
match_id: {
type:Number,
required:true
},
season: {
type:Number,
required:true
}
.....
.....
});
Also, your getmatches function requires a limit passed as the second parameter, you need to pass that as well in the code.

Related

Using Mongo/Mongoose, why is an entirely new database created when adding a document to an existing collection?

https://i.imgur.com/w5quRwA.jpg
I manually created a database called "shoppingitems" on the mongodb website console. I then created a model called "products" in an Express app and connected to the database. A collection called "products" was added to the "shoppingitems" database like I expected.
I then went to add a document to the "shoppingitems.products" collection, but instead an entirely new database called "test" was created, with a products collection and my submitted document in that 'test.products" collection instead of the "shoppingitems.products" collection like I intended.
Is there something wrong with my code? I make no mention of a "test" database anywhere, so IDK why it was created in the first place.
index.js
//Express
var express = require("express");
const app = express();
app.use(express.json());
//Mongoose
const dotenv = require("dotenv");
dotenv.config();
const mongoose = require("mongoose");
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("db connection succesfull"))
.catch((err) => console.log(err));
//CORS
const cors = require("cors");
app.use(cors());
//Routes
const productRoute = require("./routes/products");
app.use("/", productRoute);
//RUN INDEX.JS
app.listen(5000, () => {
console.log("backend server is running");
});
routes/products.js
var express = require("express");
var router = express.Router();
var Product = require("../models/Products");
/* GET PRODUCTS FOR HOMEPAGE */
router.get("/", async (req, res) => {
try {
productList = await Product.find();
res.json(productList);
} catch (error) {
console.log(error);
}
});
//POST PRODUCTS TO DATABASE
router.post("/", async (request, response) => {
console.log("request.body= ", request.body);
const newProduct = new Product(request.body);
try {
const savedProduct = await newProduct.save();
response.status(201).json(savedProduct);
} catch (err) {
response.status(500).json(err);
}
});
module.exports = router;
models/Products.js
const mongoose = require("mongoose");
const ProductSchema = new mongoose.Schema({
name: { type: String },
price: { type: Number },
description: { type: String },
image: { type: String },
stripeId: { type: String },
});
module.exports = mongoose.model("Product", ProductSchema);
Am I missing something? I don't see anything in the code that would be causing this and creating a "test" database. I've only used Mongo once or twice before though so I'm not exactly an expert. Can anybody here see what I'm doing wrong?
I'll post any additional code or information that you think is necessary to solving this. Just tell me what else you need to see.
test is the default database name used if you don't specify one. I also notice that nowhere in the code is a shoppingsitems database mentioned.
The connection string could contain the database name, but in this code that is taken from an environment variable.

The module send the empty data in the database can not retrive the body value from the request of body?

Here is my code whic is used to send the name of category and its slug in the database but its send the empty value only the id in the database I think it cannot retrive the name and slug name frome the body of request.aur maybe its retrive it aur doest not trnafer its json
const express = require('express');
const router=express.Router();
const { body, validationResult } = require('express-validator');
const Category =require('../models/Category');
//route1:add a category using post "/api/authent/addcategory". login req
router.post('/addcategory',[
body('name', 'you enter wrong name').isLength({ min: 2 }),
body('slug', 'Please enter at least 2 characters').isLength({ min: 2 }),
],async(req,res)=>{
try {
const { name, slug } = req.body;
//if there are errors ,return bad request and the error
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const cat = new Category({
name,slug
})
const savecat=await cat.save();
res.json(savecat);
} catch (error) {
}
});
module.exports=router;
Here is the models of category where I created the name and the slug of category I added it for your assistense.
const mongoose = require('mongoose');
const { schema } = require('./User');
const { Schema } = mongoose;
const CategorySchema=new Schema({
name:{
type:String,
required:true,
trim:true
},
slug:{
type:String,
required:true,
unique:true
},
parentId:{
type:String
}
});
const Category=mongoose.model('Category',CategorySchema);
module.exports=Category;
Here is my index.js
const connectToMongo=require('./db');
var cors = require('cors');
const express = require('express')
connectToMongo();
const app = express()
app.use(cors())
const port = 5000
app.use(express.json());
app.use('/api/authent',require('./routes/authent'))
app.use('/api/Categories',require('./routes/Categories'))
app.listen(port, () => {
console.log(`iNoteBook Backend listening on port ${port}`)
})
The header I added it content type:Json application

*Uncaught (in promise) TypeError:) Unable to retrieve array/collection from MongoDB Atlas

I am a beginner at Express and Mongoose and for learning I am trying to retrieve an object from the MongoDB Atlas using Mongoose.Model. I have created the collections schema in CoursesModel.js and I am trying to retrieve it in a get request from the database using Model.find().then() but it returns nothing. I want to know where I am messing it up.
CourseModel.js
const Mongoose= require("mongoose");
const Course_schema=Mongoose.Schema;
const CourseObj=new Course_schema({
type: {type:String, required:true},
Uni:{type:String, required:true},
Level:{type:String, required:true},
Programs:{type:String, required:true},
Availability:{type:String, required:true},
Language:{type:String, required:true},
Name:{type:String, required:true},
img:{type:String, required:true}
})
const Course_Model= Mongoose.model("Courses",CourseObj);
module.exports.Course_Model=Course_Model;
Index.js
const {res}=require("express");
const expressModule=require("express");
var bodyParser = require("body-parser");
const mongoose= require("mongoose");
const app= expressModule();
app.use(expressModule.json());
const Course_Collection=require("./CourseDb");
const course_model=Course_Collection.Course_Model;
//Connection establishes successfully
mongoose.connect("mongodb+srv://admin1:12345#cluster1.hojfs.mongodb.net/Edx?retryWrites=true&w=majority",{ useUnifiedTopology: true, useNewUrlParser: true}
).then((res)=>{
console.log("Database Connected"+res);
}).catch((err)=>{
console.log(err);
});
app.listen(3000,()=>{
console.log("Server listening at port 3000")
})
app.get("/addCourses",(request,response)=>{
response.header("Access-Control-Allow-Origin","*");
console.log("Get function called at server");
course_model.find().then(
(Courses)=>{
console.log("List of courses:"+Courses[0]);//trying to get the first object but its undefined
response.send(Courses);
}
).catch((err)=>{
console.log(err);
})
})
well first you can try the request in postman for easy verification . to be a 100 % sure it's coming form the api . second apply this :
in your model exports :
change :
const Course_Model= Mongoose.model("Courses",CourseObj);
module.exports.Course_Model=Course_Model;
to :
exports.Course_Model= Mongoose.model("Courses",CourseObj);
in your index
const {Course_Model}=require("./CourseDb");
const express = require('express');
const router = express.Router();
router.get("/addCourses",async (request,response)=>{
try{
response.header("Access-Control-Allow-Origin","*");
console.log("Get function called at server");
const list = await Course_Model.find();
if(list){
response.status(200).json({ list});
}
}
catch(error){
response.status(404).json({error});
}
})
let me know if it helps .

$lookup using mongoose Nodejs

I am using Nodejs(express) using Mongoose to connect with MongoDB.
Here two collections which where created using Mongoose schema in other API calls. For one API call request, i need to join these two collections and create the new collection (testalluser)which contains the new consolidated output.
And need to find all documents and send the output in the response to API call.
Note: I tried creating the Model also , but it not worked.
Query working fine inside DB .But in Mongoose, I am getting only empty array as the output .could you please help me to apply this logic in to Mongoose in NodeJS.
db.getallusers.aggregate([
{
"$lookup": {
"from": "getallusersroles",
"localField": "userRefID",
"foreignField": "userRefID",
"as": "role"
}
},
{ $merge: { into: "testalluser" } }
]).pretty()
Collection 1 Schema:getAllUsers
var mongoose = require('mongoose');
const getAllUsersDataSchema = new mongoose.Schema({
userRefID:String ,
userName:String,
divisionId: String,
divisionName:String,
emailId :String,
})
module.exports = getAllUsers = mongoose.model('getAllUsers',getAllUsersDataSchema );
Collection 2 getAllUsersRoles
var mongoose = require('mongoose');
const getAllUsersRolesDataSchema = new mongoose.Schema({
userRefID:String ,
skillRefId: String,
queueName:String,
})
module.exports = getAllUsersRoles = mongoose.model('getAllUsersRoles',getAllUsersRolesDataSchema);
Collection 3: testalluser(i Tried but i am not sure its needed)
var mongoose = require('mongoose');
const getAllCustomUsersDataSchema = new mongoose.Schema({
divisionId: String,
divisionName:String,
emailId :String,
role: Array,
userRefID:String ,
userName:String,
})
module.exports = testalluser = mongoose.model('testalluser',getAllCustomUsersDataSchema);
NodeJs Code:
const express = require('express');
const router = express.Router();
const request = require('request');
const config = require('../config');
const fs = require('fs');
const getAllUsers = require ('../db/getAllUsersListmodel');
const getAllUsersRoles = require ('../db/getetUserRolesListModel');
const testalluser =require('../db/getCustomUserListModel');
var mongoose = require('mongoose');
mongoose.connect ('mongodb://localhost/testdb',{ useUnifiedTopology: true , useNewUrlParser: true });
router.get('/', (req, res) => {
// token in session -> get user data and send it back to the Angular app
// Empty up the already existing documents inside this collection
testalluser.deleteMany({},()=>{
//Here i am trying to aggregate
getAllUsers.aggregate([
{
"$lookup": {
"from": "getallusersroles",
"localField": "userRefID",
"foreignField": "userRefID",
"as": "role"
}
},
{ $merge: { into: "testalluser" } } // creating this doc first time
]).
// Here i am trying to find the docs in this newly created collection
testalluser.find((err,getusers)=>{
if(err){
console.log(err)
}
else{
res.send(getusers);
console.log(getusers);
}
})
})
});
module.exports = router;

Can't canonicalize query: IndexNotFound: text index required for $text query', code: 17287

The error is triggered in the Product.find statement below:
var bodyparser = require('body-parser');
var express = require('express');
var status = require('http-status');
var _ = require('underscore');
var mongoose = require('mongoose');
var productSchema = require('./product');
var schema = new mongoose.Schema(productSchema);
schema.index({ name: 'text' });
module.exports = function(wagner) {
var api = express.Router();
api.use(bodyparser.json());
api.get('/product/text/:query', wagner.invoke(function(Product) {
return function(req, res) {
console.log("we are in the get " + req.params.query);
Product.
find(
{ $text : { $search : req.params.query } },
{ score : { $meta: 'textScore' } }).
sort({ score: { $meta : 'textScore' } }).
limit(10).
exec(handleMany.bind(null, 'products', res));
};
}));
return api;
};
function handleMany(property, res, error, result) {
console.log("We are handling the many");
if (error) {
console.log(error);
return res.
status(status.INTERNAL_SERVER_ERROR).
json({ error: error.toString() });
}
var json = {};
json[property] = result;
res.json(json);
}
I'm running MongoDB 3.4.2 on windows 10. I explicitly ran the statement db.products.ensureIndex({name: "text"}); in the MongoDB shell and for the first time I didn't get the error. It still gets timeout errors intermittently, though, when the query takes more than 2000 ms. I thought that I didn't have to explicitly add an index in the MongoDB shell because I'm putting on a schema index in the above code, but I don't know for sure.
Thanks,
William
I got into the MongoDB shell and put the index on the products collection like this:
db.products.createIndex({name: "text"})
That was my solution, and it worked, but I don't know if there was a glitch somewhere that made that solution necessary.

Categories

Resources