Problem with node.js and Mongo with the conexion - node.js

enter image description here
I try to do in visual Studio Code
I donĀ“t find any requre for these problem, I can`t conected with mongoDB
const mongoose = require("mongoose");
const Contact = require(__dirname + "/models/contact");
mongoose.set("strictQuery", false);
mongoose.connect("mongodb://localhost:27017/contacts");
let contactX = new Contact({
name: "Juan",
telephone: "611885599",
age: 70,
});
contactX
.save()
.then((result) => {
console.log("Contact added:", result);
})
.catch((error) => {
console.log("ERROR adding contact:", error);
});

Related

mongoose database error query executed how to fix as you can see in the image what happiendim using latest mongoose and i tryed sevrel time

require('dotenv').config()
const mongoose = require("mongoose");
const logger = require("./logger");
module.exports = {
init: async () => {
mongoose.Promise = global.Promise;
mongoose.connection.on("err", (err) => {
logger.error(`Mongoose connection error: ${err.stack}`, {
label: "Database",
});
});
mongoose.connection.on("disconnected", () => {
logger.error(`Mongoose connection lost`, { label: "Database" });
});
mongoose.connection.on("connected", () => {
logger.info(`Mongoose connection connected`, { label: "Database" });
});
mongoose.set("useNewUrlParser", true);
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);
await mongoose
.connect(process.env.MONGO)
.catch((e) => {
logger.error(e.message, { label: "Database" });
process.exit(1);
});
return true;
},
};
Error:
[unhandledRejection] Query was already executed: guild.findOne({ guildId: 'idnumber' })
I am trying to fix it and still having the query error as shown in the image. I am using latest mongoose.

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

Node + Express: How to retrieve data from MongoDB via Azure

I am a frontend developer. A colleague has kindly built me a MongoDB/Cosmos database in Azure and allowed me to retrieve a single record into my frontend. He has since gone on holiday with no cover.
(I am confused what type of database it is, since it says Azure Cosmos DB in Azure portal, but all the code in my server.js file refers to a MongoDB.) Server.js:
const express = require('express');
const app = express();
const url = 'mongodb://blah.azure.com';
app.use(express.static('static'));
const mongoClient = require('mongodb').MongoClient
let db;
app.listen(process.env.PORT || 3000, async () => {
console.log('App listening on port 3000!')
const connect = await mongoClient.connect(url)
db = connect.db('ideas');
});
app.get('/api/ideas/:name', async (req, res) => {
return res.json(await db.collection('container1').findOne({key: req.params.name}));
});
I want to retrieve all documents in this database. They each have an ID. But my colleague seems to have defined an API by name. From the MongoDB docs I can use the command find({}) instead of findOne({key: req.params.name}) to return all records, but this does not work (i.e. I get no output to the console). I presume this is because of the '/api/ideas/:name'.
I have also tried:
db.open(function(err, db){
var collection = db.collection("container1");
collection.find().toArray(function(err2, docs){
console.log('retrieved:');
console.log(docs);
})
})
but i get an error that tells me I can't retrieve the property "open" of undefined.
Can anyone help me either: (1) work out how to change the API in Azure, or (2) rewrite this code to retrieve all records? I will also need to edit and insert records. Thanks
If you want to retrive data from Mongo DB in nodejs espresso application, I suggest you use the package mongoose.
For example
Create mongo.js file to add connection details
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const accountName= 'testmongo05',
const databaseName= 'test',
const key= encodeURIComponent(''),
const port: 10255
const mongoUri = `mongodb://${env.accountName}:${key}#${accountName}.documents.azure.com:${port}/${databaseName}?ssl=true`;
function connect() {
mongoose.set('debug', true);
return mongoose.connect(mongoUri, {
useFindAndModify : false,
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
});
}
module.exports = {
connect,
mongoose
};
Define models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
userId: {
type: String,
required: true,
unique: true
},
name: String,
saying: String
},
{
collection: 'Users'
}
);
const User = mongoose.model('User', userSchema);
module.exports = User;
CURD operations
const express = require('express');
const bodyParser = require('body-parser');
const User = require('./module/user');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
require('./mongo').connect().catch(error => console.log(error));
//list users
app.get('api/users', async (req, res) => {
const docquery = User.find({});
await docquery
.exec()
.then(users => {
res.status(200).json(users);
})
.catch(error => {
res.status(500).send(error);
});
});
// get user by userId
app.get('/api/user/:uid', async (req, res) => {
const docquery =User.findOne({userId:req.params.uid })
await docquery
.exec()
.then(user => {
if (!checkFound(res, user)) return;
res.status(200).json(user);
})
.catch(error => {
res.status(500).send(error);
});
});
// create
app.post('/api/user', async (req, res) => {
const originalUser= { userId: req.body.userId, name: req.body.name, saying: req.body.saying };
const user = new User(originalUser);
await user.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json('User created successfully!');
console.log('User created successfully!');
});
});
//update user by userId
app.put('/api/user/:uid', async (req, res) => {
const docquery =User.findOneAndUpdate({userId: req.params.uid}, req.body)
await docquery.exec()
.then((user) =>{
if (!checkFound(res, user)) return;
res.status(200).json("User update successfully");
console.log('User update successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
//delete user by userId
app.delete('/api/user/:uid', async (req, res) => {
const docquery = User.findOneAndRemove({userId: req.params.uid })
await docquery.exec()
.then(user =>{
if (!checkFound(res, user)) return;
res.status(200).json("user deleted successfully!");
console.log('user deleted successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
function checkFound(res, user) {
if (!user) {
res.status(404).send('user not found.');
return;
}
return user;
}
Test
a. Create user
b. get user
c. List Users
d. Update User
e delete user

How can I implement transaction concept in mongoose model?

I have three models "userLogin.js","userDetail.js",and "userAddress.js".I want data should be stored simultaneously, if any error occurs it should rolback all the insert actions.this what I have tried. I gives me the error user is not defined . when try to fix them it gives the error "schema is not registered"
const UserLogin=require("../models/userLogin");
const UserDeatil=require("../models/userDetail");
var myModelSchema1 = require('mongoose').model('UserLogin').schema;
var myModelSchema2 = require('mongoose').model('UserDeatils').schema;
exports.user_signup = (req, res, next) => {
UserLogin.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new UserLogin({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash,
loginDate:req.body.logindate,
});
const userdetils = new UserDeatil({
_id: new mongoose.Types.ObjectId(),
userId:result.userID,
userName:req.body.username,
dob:req.body.dob,
gender:req.body.gender,
photo: req.file? req.file.path : null,
imei:req.body.imei,
});
insertUsers();
}
});
}
});
};
async function insertUsers(){
try{
const id= transaction.insert(myModelSchema1, user);
const id1= transaction.insert(myModelSchema2, userdetils);
const final = await transaction.run();
}
catch(error){
console.error(error);
const rollbackObj = await transaction.rollback().catch(console.error);
transaction.clean();
c
}
}
first when you define your users schema the email must be uniqe wich when fails when you tries to create anothe user document with the same email,
and with this convention you can move forward like this:
const UserLogin=require("../models/userLogin");
const UserDeatil=require("../models/userDetail");
cosnt signup = async (req ,res)=>{
const { email , password ,...details} = req.body
const createdDocs = []
const hashedPwd = hash(password);
try{
const user = new UserLogin({ email , password: hashedPwd });
await user.save()
createdDocs.push(user)
const userDetails = new UserDetails({...details,userId:user._id});
await userDetails.save()
createdDocs.push(userDetails)
catch(err){
res.json({ status:false, message:err.message})
//emulates the rollback when any thing fails on the try flow
if(createdDocs.length){
const operationsToRollBack = createdDocs.map(doc=>doc.remove)
await Promise.all(operationsToRollBack)
}
}
MongoDB supports multi-document transactions starting from version 4.0.
Ideally, if you need a transactional database you would use an SQL type db.
But if you would still like to enjoy MongoDB while needing transactions, they have introduced an API for this - https://docs.mongodb.com/manual/core/transactions/

Node Rest API issue with controller

I developed my node rest api as usual but this time it is showing some invalid error in controller.js file. The mongoose is not getting required. When I hit the API in postman, it gives the error as :
{
"error": {
"message": "Tweets is not a constructor"
}
}
I even updated my packages for the same, but nothing seems to work. Here is the snippet of my controller for tweets.js:
const mongoose = require('mongoose');
const Tweets = require('../models/tweets');
exports.get_all_tweets = (req, res, next) => {
Tweets.find()
.exec()
.then(docs => {
console.log(docs);
res.status(200).json(docs);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
exports.create_tweets = (req, res, next) => {
const tweetbody = req.body;
tweetbody._id = mongoose.Types.ObjectId();
const tweet = new Tweets(tweetbody);
tweet
.save()
.then(docs => {
console.log(docs, 'Tweets');
res.status(200).json(docs);
})
.catch(err => {
console.log(err, 'error found');
res.status(500).json({
error:err
});
});
The first mongoose line is appearing blank as shown in the screenshot:
mongoose
Model for tweets.js:
const mongoose = require('mongoose');
const tweetSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
time: { type: String},
count: { type: Number}
});
module.export = mongoose.model('Tweets', tweetSchema);
please check all path and add new keyword before schema initializing
Model for tweets.js:
const tweetSchema = new mongoose.Schema({
Try this using async/await
exports.get_all_tweets = async (req, res, next) => {
const result = await Tweets.find()
res.status(200).json(result);
}
module.exports with a 's' at the end :)

Resources