$lookup using mongoose Nodejs - javascript

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;

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.

*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 .

Mongoose : usr.findOneAndUpdate is not a function

Error : usr.findOneAndUpdate is not a function
Model:
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt')
var schema = new Schema({
email: { type: String, require: true },
username: { type: String, require: true },
password: { type: String, require: true },
creation_dt: { type: String, require: true },
tasks:[{type:{type:String}}]
});
module.exports = mongoose.model('User',schema)
i want to Add some Task in tasks array so i use post method for That and code is
Code:
router.post('/newTask', function (req, res, next) {
var dataa = {
pName: req.body.pName,
pTitle: req.body.pTitle,
pStartTime: req.body.pStartTime,
pEndTime: req.body.pEndTime,
pSessionTime: req.body.pSessionTime
}
var usr = new User(req.user)
usr.findOneAndUpdate(
{_id:req.user._id},
{$push:{tasks:dataa}}
)
try {
doc = usr.save();
return res.status(201).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
})
i also read the documentation of findOneAndUpdate but i din't get solution please someone can Help out of this error....
Thank You.
You need to import your model into the file containing your routes. All mongoose methods are based off the schema that you define, not new instances you create.
For example, if you have a User model that looks like this:
// file is named user.js
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema ({
username: String,
password: String
})
module.exports = mongoose.model("User", userSchema)
You need to import the model so mongoose recognizes it as one
Like so (assuming the routes file and user model file are in the same directory):
const User = require("./user")
router.post("/newTask", (req, res) => {
User.findOneAndUpdate(//whatever you want to be updated)
})

is this code true to query all documents in mongodb via mongoose?

i'm using MongooseJS and doesn't return anything in console or res.json
is it about find function ?
const router = require("express").Router();
var Panel = require("../models/Panel");
router.get("/panels", (req, res) => {
Panel.find({}, function(err, panels) {
if (err) res.send(err);
console.log(panels);
res.json(panels);
});
});
This is the mongoose model for Panel section
const mongoose = require("mongoose");
const Panel = mongoose.model(
"Panel",
new mongoose.Schema({
name: String,
const: Number,
salons: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Salon"
}
]
})
);
module.exports = Panel;
Problem solved, by catching errors, and trying to use anyone can access database, it was about my proxy :)

Getting error in nodejs when querying mongodb data?

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.

Categories

Resources