Unable to insert record into mongodb using Node.js - 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(){})

Related

Getting an empty array Mongoose

I can not get data from my MongoDb collection via mongoose - I'm getting an empty array out of my request. It only happens when I'm using a route which I posted below.
Code
router.get("/options", async (req,res) => {
try {
const { animalClass} = req.body;
if (!animalClass) {
const animalClasses = await AnimalClass.find({});
console.log(animalClasses);
return res
.status(200)
.json({animalClasses})
} else {
const animalTypes = await AnimalType.find({class: animalClass});
console.log(animalTypes);
return res
.status(200)
.json({animalTypes})
}
} catch (err) {
res
.status(500)
.json({msg: err})
}
});
Schema
const mongoose = require('mongoose');
const animalClassSchema = new mongoose.Schema({
name: {type: String, required: true}
})
module.exports = AnimalClass = mongoose.model('animalClass',animalClassSchema);
Specify the collection name when creating the schema, like:
const animalClassSchema = new mongoose.Schema({
name: {type: String, required: true}
}, { collection: 'animalClass' });
By default, Mongoose pluralizes your collection name. This option allows you to override that behavior. More info in the docs:
https://mongoosejs.com/docs/guide.html#collection

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

Getting NULL data from collection from MongoDB Atlas

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

Mongo data being removed when I restart my NodeJS/Koa.app using Mongoose

I am having an issue whereas any data that exists in my MongoDB instance is being removed when I restart my Node/Koa.app. This application uses Mongoose to connect to the local Mongo instance.
Here is my code:
app.js (I have code in there to output connection to the logger)
import Koa from 'koa';
import path from 'path';
import bodyParser from 'koa-bodyparser';
import serve from 'koa-static';
import mongoose from 'mongoose';
import Config from '../Config.js';
global.appRoot = path.resolve(__dirname);
const app = new Koa();
mongoose.connect(Config.mongo.url);
mongoose.connection.on('connected', (response) => {
console.log('Connected to mongo server.');
//trying to get collection names
let names = mongoose.connection.db.listCollections().toArray(function(err, names) {
if (err) {
console.log(err);
}
else {
names.forEach(function(e,i,a) {
mongoose.connection.db.dropCollection(e.name);
console.log("--->>", e.name);
});
}
});
});
mongoose.connection.on('error', (err) => {
console.log(err);
});
The MongoDB config url being referenced in the above module is:
mongo: {
url: 'mongodb://localhost:27017/degould_login'
}
and my Mongoose model:
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
let UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
groupForUsers: [{ type: Schema.Types.ObjectId, ref: 'userGroups' }]
});
export default mongoose.model('users', UserSchema, 'users');
And one of the functions that inserts Data
async register(ctx) {
return new Promise((resolve, reject) => {
const error = this.checkRequiredVariablesEmpty(ctx, [ 'password', 'email' ]);
if(error.length) {
reject(new this.ApiResponse({
success: false,
extras: {
msg: this.ApiMessages.REQUIRED_REGISTRAION_DETAILS_NOT_SET,
missingFields: error
}}
));
}
this.userModel.findOne({ email: ctx.request.body.email }, (err, user) => {
if(err) {
reject(new this.ApiResponse({ success: false, extras: { msg: this.ApiMessages.DB_ERROR }}));
}
if(!user) {
let newUser = new this.userModel();
newUser.email = ctx.request.body.email;
newUser.username = ctx.request.body.username;
newUser.password = ctx.request.body.password;
newUser.save()
.then((err, insertedRecord) => {
When I start the app and populate data into the MongoDB using the register function I can see the data saves into the MongoDB instance correctly.
However, when restarting the application all of these records get removed Is there anything that is causing this in my code? It's impossible for me to have to keep inputting data on every app restart during development.
Your issue is with this line:
mongoose.connection.db.dropCollection(e.name);
...where your collections are being dropped on mongoose 'connected' event.

MongoDB: mongod shows that my app is not authorized

I have installed mongodb and my mongodb and db folders are C:/mongoDB/bin and C:/data/db respectively. I have also setup admin user as stated on
https://docs.mongodb.com/manual/tutorial/enable-authentication/
Now i want to perform basic CRUD operations requiring both read and write on a database mApp through Express and Mongoose. I am providing code for both app and schema below.
Code is well documented so that it is easy to understand.
App.js
var express = require('express');
var app = express();
//Invoking user
var User = require('./schema.js');
//Creating an employee object by giving values to all properties
var User1 = new User({
name: 'Anurag',
username: 'Anurag2',
password: 'abc',
admin: false,
location: 'somewhere',
meta: {
age: 25,
website: 'abc.com'
},
createdAt: 'Jun 11 2017',
updatedAt: 'Jun 11 2017'
}); //Remember to provide all records,otherwise document wont be saved.
//CRUD start. Creating a user document
User1.save(function(err, employ, num) {
if (err) {
console.log('error occurred');
}
console.log('saved ' + num + ' record');
console.log('Details ' + employ);
});
/* To retrieve documents from database, you can retrieve all at
once, or one at a time by find(), findById(), findOne() */
//To retrieve all documents
User.find({}, function(err, data) {
if (err) {
console.log('error occurred while retrieving all docs');
}
console.log(data);
});
User.findOne({
username: 'Anurag2'
}, function(err, data) {
if (err) {
console.log('error in finding one document');
}
console.log(data);
});
User.update({
location: 'someplace'
}, {
location: 'anything'
}, function(err) {
if (err) {
console.log('error in updating');
}
console.log('updated');
});
//update one document
User.findOneAndUpdate({
username: 'Anurag2'
}, {
admin: true
}, function(err, data) {
if (err) {
console.log('error in finding and updating');
}
console.log('updated' + data);
});
//Delete a user document
User.remove({
location: 'anywhere'
}, function(err) {
if (err) {
console.log('error occurred');
}
console.log('removed');
});
DB Schema(schema.js)
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mApp'); //myApp is the database being connected here.
//now we open a connection
var db = mongoose.connection;
db.once('open', function() {
console.log('Connected to Database');
});
db.on('error', console.error.bind(console, 'connection error'));
//initialising a schema
var Schema = mongoose.Schema;
mongoose.Promise = require('bluebird'); //used as mpromise was showing deprecated on console.
//creating a schema
var userSchema = new Schema({
name: String,
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
Required: true
},
admin: Boolean,
location: String,
meta: {
age: Number,
website: String
},
createdAt: Date,
updatedAt: Date
});
//creating a model that uses this schema
var User = mongoose.model('User', userSchema);
//now we export this model
module.exports = User;
Now, I login in mongo through admin and i changed the db to mApp. I run the app through node.
The mongod console shows I am not authorized to perform any actions on the app.
No query gets executed and I get all error messages. Why is this happening? Please help me with this.
You have been enable authentication for your database.
So, you have to provide the corresponding credentials in your connection string
Change:
mongoose.connect('mongodb://localhost/mApp');
To
mongoose.connect('mongodb://username:password#host:port/database');
More information on mongoose documentation

Resources