Getting NULL data from collection from MongoDB Atlas - node.js

I have connected my code to MongoDB Atlas using Mongoose... even though the collection has a data in it its shows null in response.
I want to know the exact issue and troubleshoot it, because the collection has the data required
Collection details are in this image:
1. Connectivity Code -
const mongoose = require('mongoose')
const uri = "mongodb+srv://<user>:<password>#cluster0-3awwl.mongodb.net/";
mongoose.connect(uri, {
dbName: 'bing_bot'
}).catch((e) => {
console.log('Database connectivity error ', e)
})
2.Model-
const mongoose = require('mongoose')
const Student = mongoose.model('student', {
StudentName: {
type:String
},
Contact: {
type:String
},
Email: {
type:String
},
BNo: {
type:String
},
Year: {
type:String
}
})
module.exports = Student`enter code here`
3. Retrieve data -
Student.findById(_id).then((data) => {
console.log('data: ', data)})
4. Using MongoCLient
const uri = "mongodb+srv://<user>:<password>#cluster0-3awwl.mongodb.net/bing_bot"
MongoClient.connect(uri, function(err, client) {
if(err) {
console.log('Error occurred while connecting to MongoDB Atlas...\n', err);
}
console.log('Connected...');
const collection = client.db("bing_bot").collection("student");
// perform actions on the collection object
collection.findOne({
"StudentName": "Test"
}).then((d) => {
console.log('data: ', d)
})
const data = collection.find()
console.log('data:1 ', data)
client.close();
});

It's because the mongoose instances in your Connectivity Code and Model are different and unrelated. One is connected (Connectivity), but the other (Model) is not. You've to use the same instance so export one mongoose and import that where required.
// connectivityCode.js
const mongoose = require('mongoose')
const uri = "mongodb+srv://<user>:<password>#cluster0-3awwl.mongodb.net/";
mongoose.connect(uri, {
dbName: 'bing_bot'
}).catch((e)=>{
console.log('Database connectivity error ',e)
})
module.exports = mongoose; // <-- exporting
// model.js
const mongoose = require('./connectivityCode.js') // <-- importing
// rest of the code

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);
}

How to get MongoDB _id of an inserted document

I want to create a document in my MongoDB database and take the _id of the new document.
This is what I'm doing:
const mongoose = require("mongoose");
const billingSchema = require("./models/billing");
const { ObjectId } = require("bson");
const { MongoClient } = require("mongodb");
const mongouri = "***";
var connection = mongoose.createConnection(mongouri);
var Bills = connection.model("Fatturazione", billingSchema, "Fatturazione");
exports.createBill = (b) => {
return new Promise((resolve, reject) => {
Bills.Create(b, function (err) {
if (err) {
reject(err);
} else {
console.log(mongoose.Types.ObjectId(b._id));
resolve();
}
});
});
};
and this is my Schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//schema define the structure of the document
const billingSchema = new Schema({
data_fatturazione: {
type: Date,
required: true,
},
data_saldo: {
type: Date,
required: false,
},
totale: {
type: Number,
required: false,
},
pagato: {
type: Boolean,
required: false,
},
});
module.exports = billingSchema;
In the console.log() I want to print the _id of the last inserted document but it prints a non-existing id (it doesn't correspond to the _id of the last created document in the database). I also tried without using mongoose.Types.ObjectId() but it prints undefined. I don't understand where is the problem.
I call the function createBill() in another js file, passing an object with the correct fields.
You are trying to get the _id of argument b, which is passed to your createBill, which is logically undefined. Instead you must get the _id from a result of Bill.create, mongoose callbacks take 2 arguments as #Joe mentioned in the comments, so your code must look like this:
exports.createBill = (b) => {
return new Promise((resolve, reject) => {
Bills.Create(b, function (err, result) {
if (err) {
reject(err);
} else {
console.log(result._id);
resolve(result);
}
});
});
};

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

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

Unable to insert record into mongodb using Node.js

I am trying to save record into mongodb using node.js and for that purpose I am using mongoose driver but here I am unable to insert record into mongodb. I am explaining my code below.
mongo.util.js:
const mongoose = require('mongoose').Mongoose;
const config = require('../../config/settings');
const mongooseInstance = new mongoose();
const url = `mongodb://${config.MONGO_USER}:${config.MONGO_PWD}#${config.MONGO_URL}/${config.MONGO_DB}`;
const options = {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
};
/*
1- Connect to mongo server
*/
mongooseInstance.connect(url, options, (err) => {
if(!err) {
console.log('Mongodb connection successed');
} else {
console.log('Error in DB connection:' + JSON.stringify(err, undefined, true));
}
})
module.exports = mongooseInstance;
This file is my connection file where I can connect to my local mongodb. This file has included into mt app.js file and I am getting the message as Mongodb connection successed.
users.model.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = new Schema({
name: {type: String},
mobile: { type: String},
password: { type: String},
email: { type: String},
city: { type: String}
}, {
timestamps: {
CreatedAt: 'CreatedAt',
UpdatedAt: 'UpdatedAt'
}
});
module.exports = mongoose.model('customers', User);
The above file is my schema file where I am trying to design schema for customer collection.
users.service.js:
const _ = require('lodash'),
axios = require('axios'),
model = require('../model/users.model');
async registerUser(req) {
try{
const data = req.body;
console.log('data', data);
const user = await model.create(data);
if (!user) {
return {
data: user,
error: true,
msg: 'User Registeration failed'
}
}else {
return {
data: user,
error: false,
msg: 'User Registered successfully'
}
}
}catch(error) {
console.log('Error in registerUser service::', error);
}
}
Here I trying to insert the record but when this function is called no record is inserting into mongodb even no customer collection is there. Here I need to insert record using this mongoose driver.
Try as below
Step 1: create object out of User model
var user = new model(req.body)
Step 2: then call
user.save(function(){})

Getting error while adding record into mongodb using mongoose and Node.js

I am getting the following error while adding some record into mongodb.
Error:
User.create is not a function /--/ "TypeError: User.create is not a
function\n at module.exports.createUsers
Here I am sending some data from postman and my aim is add them into mongodb database. I am explaining my mongo connect file first.
mongo.js:
const mongoose = require('mongoose').Mongoose;
const config = require('../config/settings');
const { MONGO_DB } = require('../config/settings');
const mongooseInstance = new mongoose();
const url = `mongodb://${config.MONGO_USER}:${config.MONGO_PWD}#${config.MONGO_URL}/${MONGO_DB}`;
const options = {
useNewUrlParser: true,
useCreateIndex: true,
connectTimeoutMS: 5000000,
poolSize: 10000,
useUnifiedTopology: true
};
/*
1- Connect to mongo server
*/
mongooseInstance.connect(url, options, (err) => {
if(!err) {
console.log('Mongodb connection successed');
} else {
console.log('Error in DB connection:' + JSON.stringify(err, undefined, true));
}
})
module.exports = mongooseInstance;
The above file used to make connection to my mongodb. I am explaining my code below.
user.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = new Schema({
name: {type: String},
mobile: { type: String},
email: { type: String},
city: { type: String}
}, {
timestamps: {
CreatedAt: 'CreatedAt',
UpdatedAt: 'UpdatedAt'
},
collection : 'user'
});
module.exports = User;
The above file is my model file. my controller file is given below.
user-controller.js:
const User = require('../models/user');
/*
1- Add user.
*/
module.exports.createUsers = function (req, res,next) {
const data = req.body;
user = User.create(data);
if(!user) {
return res.status(400).json({ success: false, res: []}).end('');
} else {
return res.status(200).json({ success: true, res: user}).end('');
}
}
Here I am trying to create the record but getting the above issue. I need to add record to user collection. Please help me to resolve this issue.
You need to create a model first of your schema.
Simply create it with the following command and export the variable:
const userModel = mongoose.model('user', User);
module.exports = userModel;
In user.js change...
module.exports = User;
to...
module.exports = mongoose.model("User", User)
In your user.js file, you need to update module.exports = User with module.exports = mongoose.model("User", User). Because in Mongoose, models are defined by passing a Schema instance to mongoose.model.
Try to modify your modals' export statement as
const User = module.exports = mongoose.model('User', User);

Resources