Can't upload a document to my mongoDB server - node.js

I am studying on my own node.js and I am following codewithmosh website.
The thing is, is that I try to upload a new object to my mongo database using compass.
I have the following code (see screenshots for outputs) and there is no error and on mosh'es tutorial everything is working great.
The problem I have is that my server isn't being updated with the new document.
Any idea what I am missing?
I refreshed the compass a few times and nothing changes.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true , useUnifiedTopology: true}).then(() =>
console.log('connected to MongoDB')
).catch((err) => console / log('Could not connect to MongoDB', err));
const courseSchema = new mongoose.Schema({
name: String,
author:String,
tags: [String],
date: {type: Date, default: Date.now},
isPublished: Boolean
})
const Course = mongoose.model('Course', courseSchema);
async function createCourse () {
const course = new Course ({
name: 'node.js Course',
author: 'Daniel',
tags: ['node', 'backend'],
isPublished: true,
});
const result = await course.save();
console.log(result);
}
createCourse();

OK I figure it out.
There was a bad configuration in my compass.
I had to go to setup a connection

Related

empty result when getting data from mongodb with mongoose and node js

I'm trying to fetch all my documents from a collection in my MongoDb DB but I can't do it. I have absolutely no error but it just returns an empty array in my console.
Model :
import mongoose from "mongoose";
const websiteSchema = mongoose.Schema({
id: {type: String},
name: {type: String, required: true},
url: {type: String, required: true},
note: {type: Number, required: true}
});
export default mongoose.model("Website", websiteSchema);
File in which I want to use the data :
import express from 'express';
import Website from '../models/website.js';
const routerWebsiteList = express.Router();
routerWebsiteList.get('/website-list', async function(req, res, next) {
try {
const websitesToCrawl = await Website.find({});
console.log(websitesToCrawl);
} catch (error) {
res.status(500).json({message : "An error occured"});
}
})
export default routerWebsiteList;
All I get in my console is [].
My data in my database seems good too :
Accully everything looking fine maybe you can use
require for import files
const name = require('name')
and for the export file :
module.exports = routerWebsiteList
after that be sure you connected your database correct like this
async function database() {
await mongoose
.connect(process.env.DATABASE_URL)
.then(() => {
console.log("Database Coonected");
})
.catch((err) => {
console.log(err);
});
}
database()
Last detail is you don't need to put id on mongoose schema just remove it and finally change your model like this
const mongoose = require("mongoose");
const websiteSchema = mongoose.Schema({
name: {type: String, required: true},
url: {type: String, required: true},
note: {type: Number, required: true}
});
const Website = mongoose.model("Website", websiteSchema);
module.exports = Website
I hope that will be helpful. If you will be stuck somewhere feel free to type here again.
I finally found what was the problem. The mongoose Schema was looking in a wrong collection named "websites". All I had to do was to specified the collection name in my model as following : ("websitesToCrawl" is the collection name)
export default mongoose.model("Website", websiteSchema, "websitesToCrawl");

can't find documents by id

so I'm trying to update a document but it just doesn't work with _id but if I filter with "name" it works
I also tried with FindByID and it returns null
using mongoose version 5.0.18
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongo-exercises')
.then(() => console.log('connected to database :)'))
.catch(reason => console.log('Can not connect to data base',reason));
const courseSchema = mongoose.Schema({
name: String,
author: String,
tags: [String],
Date: { type:Date,default:Date.now },
isPublished: Boolean,
price: Number
});
const Course = mongoose.model('courses',courseSchema);
async function updateCourse(id){
let result = await Course.update({_id: id},{
$set:{
author: "some random dude",
isPublished: true
}
});
console.log('result: ',result);
}
updateCourse('5a68fde3f09ad7646ddec17e');
try using
//make sure you import Course module
Course.findByIdAndUpdate(id)
.then(response=>{
})
.catch(err=>{
})
I just had to re-import the collection without _id so it can regenerate them

"Mongo Error : Authentication failed" can't read datas from MongoDB Atlas

Today I wanted to use clusters in MongoDB Atlas to get an online DB, instead of my MongoDB local database (which worked perfectly fine),
So, I followed a mLab tutorial,
It works perfectly on writing in the database (when I auth in my website, it adds the datas in the database, when I write a message in the chat it adds the message, etc...)
But when I want to read these datas, I got :
MongoTimeoutError: Server selection timed out after 30000 ms
MongoError: Authentication failed
The connect in my server/index.js seems to work, because I got the console log :
mongoose
.connect(
`mongodb+srv://${process.env.USER}:${process.env.PASSWORD}#ofilms-demo-f9iwz.mongodb.net/test?retryWrites=true&w=majority`,
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(() =>
console.log(
"working"
)
)
.catch(err => console.log(err));
but not other routes, like this one (which get all users in the database) :
const mongo = require("mongodb").MongoClient;
router.get("/getAll", function(req, res) {
console.log("get all users");
const client = new mongo(`mongodb+srv://${process.env.USER}:${process.env.PASSWORD}#ofilms-demo-f9iwz.mongodb.net/test?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
});
client.connect(err => {
const collection = client.db("test").collection("users");
collection.find().toArray((err, items) => {
res.json(items);
});
client.close();
});
});
One model from Mongoose :
/* eslint-disable no-undef */
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true,
lowercase: true
},
password: {
type: String,
required: true
},
firstname: String,
lastname: String,
sexe: String,
mobilePhone: String,
departement: Number,
city: String,
moviesLiked: Array,
seriesLiked: Array,
moviesDisliked: Array,
seriesDisliked: Array,
moviesFavorites: Array,
seriesFavorites: Array,
lists: Array,
creationDate: {
type: Date,
default: Date.now
},
lastConnection: Date,
isVerified: Boolean,
isAdmin: Boolean,
isModerator: Boolean,
isConnected: Boolean
});
module.exports = User = mongoose.model("users", UserSchema);
I can show you the code of other files if needed, or give you the link of the repo if someone wants it, but it's a really big project,
Thanks,
You seem to connect mongodb with both mongoose.connect() and MongoClient.connect(), one of them will be enough.
If you want to use mongoose you can connect to mongodb in your main file (index.js or app.js), and when connected to the db your server can start listening.
And you don't need to connect mongodb in your routes.
For example:
index.js (main file)
const express = require("express");
const app = express();
require("dotenv").config();
const users = require("../routes/users"); //todo: correct the users route path
app.use("/api/users", users);
mongoose
.connect(
`mongodb+srv://${process.env.USER}:${process.env.PASSWORD}#ofilms-demo-f9iwz.mongodb.net/test?retryWrites=true&w=majority`,
{ useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() => console.log("working"))
.catch(err => console.log(err));
in your route: (users.js)
const express = require("express");
const router = express.Router();
const User = require("../../models/User");
router.get("/users", async (req, res) => {
const users = await User.find({});
res.send(users);
});
module.exports = router;
As you see there is no connection related code in our route, because we have already connected when the application starts.
For this code to work, you need to add your local IP to the IP whitelist IP in mongodb atlas panel. (SECURITY --> Network Access --> IP Whitelist.
Also the user you are using to connect must have read an write priveleges.
You can check your users priveleges in SECURITY --> Database Access --> MongoDB Users.

Data seeded with Mongoose not being saved in MongoDB

I'm trying to add some data to MongoDB using Mongoose, but I'm having trouble getting that data to save to my database. I'm following this tutorial on YouTube (~11 min), but I think the video might be using a different version of Mongoose.
Basically, I have a Product schema defined in a separate JS file, and I'm running a file called productSeeder.js by running node productSeeder.js in terminal with the Mongo daemon running. When I switch to the correct database and type db.products.find() into the Mongo shell, nothing is returned to me.
My productSeeder.js file:
var Product = require('../models/product');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/shopping');
var products = [
new Product({
imagePath: 'images/dummy.png',
price: 9,
title: 'a title',
desc: 'some text'
}),
new Product({
imagePath: 'images/dummy.png',
price: 5,
title: 'a title',
desc: 'some text'
})
];
var done = 0;
for (var i = 0; i < products.length; i++) {
products[i].save(function(err, result) {
if (err) {
console.log(err);
return;
};
done++;
if (done == products.length) {
mongoose.disconnect();
};
});
};
My product.js file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
imagePath: {type: String, required: true},
price: {type: Number, required: true},
title: {type: String, required: true},
desc: {type: String, required: true}
});
module.exports = mongoose.model('Product', schema);
Thanks so much, and happy holidays!
Do you know if Mongoose has successfully been connected before you try to save the Products?
One thought could be that since the Db access is async, you're trying to save off items before the connection exists.
You could pass a callback to your connection or use an event listener and wrap your save functions in the connection callback.
mongoose.connection.on('connected', function(){
//save products here
});
I've read of a few cases of Mongoose failing to save without error.
Edit: might be better to listen for .on('open') instead (mongoose docs).

I am getting an error of mongoose is not defined

I am creating an api using MongoDB, I am using Mongoose to create Data Persistence. However I am getting an error that Mongoose is not defined, I have used require function to call the node module but it is still giving me the same error.
Below is the connection file
var mongoose = require('mongoose')
var database = 'api'
const server = 'mongodb://localhost:27017/'+database
console.log(server)
mongoose.connect(server)
const db = mongoose.connection
console.log(db)
var Schema = mongoose.Schema
var ObjectId = Schema.ObjectId
const WeatherSchema = new Schema({
id: {type: String, required: true},
name: { type: String, required: true },
items: {type: String, required: true}
})
var WeatherDB = mongoose.model('DBlist', WeatherSchema)
You should wait for the database to connect, as it doesn't happen immediately. Something like this:
var mongoose = require('mongoose');
mongoose.connect(sever);
var db = mongoose.connection;
db.on('disconnect', connect); // auto reconnecting
db.on('error', function(err) {
debug('connection error:', err);
});
db.once('open', function (callback) {
// we're in the game, start using your Schema
const WeatherSchema = new Schema({...
});
p.s.
I've added little extra sugar just to let you know these events exist and are quite helpful to understand what's going on.

Resources