mongoose .save() method don't insert the data to MonogoDB - mongodb

i do these steps in console
node
.load app.js
Massage.save()
then in mongoDB shell
use test
db.test.find()
and when i check the data base, it's empty
const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/test", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const movieSchema = mongoose.Schema({
title: String,
year: Number,
score: Number,
});
// Models
const Movie = new mongoose.model("Movie", movieSchema);
const Massage = new Movie({
title: "The Massage",
year: 1976,
score: 92,
});
app.get("/", (req, res) => {
res.send("ss");
});
app.listen(port, (req, res) => {
console.log(`http://localhost:${port}`);
});

You missed the most important part:
const Massage = await new Movie({
title: "The Massage",
year: 1976,
score: 92,
}).save();

The problem is that I did not set a collection in the model
so instead of
const Movie = new mongoose.model("Movie", movieSchema);
it should be
const Movie = new mongoose.model("Movie", movieSchema, collectionName);
when you want to extract the data from database
use database // go to the database u want
db.collection.find() // extract the data from the collection

Related

fetch data's from existing collection

I have created a MongoDB database named: "helsinki_city_bike" and I uploaded CSV data using MongoDB compass in the collection name: "journey_detail". I also connected the database to atlas using a connection string. Now that I want to fetch the data from the database it's creating another test db and collection name "journey_detail" inside "helsinki_city_bike".
how can I fetch data from my collection without creating an empty collection?
the function is working well as I am getting an empty array. what I am doing wrong with the model?
This is my schema:
import mongoose from "mongoose";
export const journeySchema = mongoose.Schema({
Departure_time: String,
Return_time: String,
Departure_Station_Id: Number,
Departure_Station_Name: String,
Return_Station_Id: Number,
Return_Station_Name: String,
Covered_Distance: Number,
Duration: Number,
});
export const journey_detail = mongoose.model("journey_detail", journeySchema);
req function:
import { journey_detail } from "../models/Schema.js";
export const getJourneyDetails = async (req, res) => {
try {
const JourneyDetails = await journey_detail.find().limit(10);
if (!JourneyDetails) {
return res.status(404).json({ message: "Journey Details not found" });
}
res.status(200).json(JourneyDetails);
} catch (error) {
console.error(error);
res.status(500).json({ message: "Error retrieving Journey Details" });
}
};
connection:
const app = express();
dotenv.config();
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
app.use("/", router);
mongoose
.connect(process.env.CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() =>
app.listen(3001, () => console.log(`server running on the port ${3001}`))
)
.catch((error) => console.log(error));
mongoose.set();
mongoose.connection.on("open", () => {
console.log("Mongoose connected.");
});

Mongoose const castError = new CastError();

I seem to be getting this error:
C:\...\node_modules\mongoose\lib\query.js:4638
const castError = new CastError();
^
CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "cProd"
at model.Query.exec (C:\...\node_modules\mongoose\lib\query.js:4638:21)
at model.Query.Query.then (C:\...\node_modules\mongoose\lib\query.js:4737:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
messageFormat: undefined,
stringValue: '"undefined"',
kind: 'ObjectId',
value: 'undefined',
path: '_id',
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters
at new BSONTypeError (C:\...\node_modules\bson\lib\error.js:41:28)
at new ObjectId (C:\...\node_modules\bson\lib\objectid.js:65:23)
at castObjectId (C:\...\node_modules\mongoose\lib\cast\objectid.js:24:12)
at ObjectId.cast (C:\...\node_modules\mongoose\lib\schema\objectid.js:247:12)
at ObjectId.SchemaType.applySetters (C:\...\node_modules\mongoose\lib\schematype.js:1180:12)
at ObjectId.SchemaType._castForQuery (C:\...\node_modules\mongoose\lib\schematype.js:1615:15)
at ObjectId.SchemaType.castForQuery (C:\...\node_modules\mongoose\lib\schematype.js:1605:15)
at ObjectId.SchemaType.castForQueryWrapper (C:\...\node_modules\mongoose\lib\schematype.js:1582:20)
at cast (C:\...\node_modules\mongoose\lib\cast.js:341:32)
at model.Query.Query.cast (C:\...\node_modules\mongoose\lib\query.js:5073:12),
valueType: 'string'
}
for this code:
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const cProd = require('./models/cProd');
mongoose.connect('mongodb://localhost:#/database', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Database connected');
});
const app = express();
// app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
// Parsing request.body
app.use(express.urlencoded({extended: true}))
app.get('/', (req, res) => {
res.render('main')
});
app.get('/cProds', async (req, res) => {
const cProds = await cProd.find({});
res.render('cProds/index', {cProds})
});
app.get('/cProds/create', (req, res) => {
res.render('cProds/create');
})
app.post('/cProds', async (req, res) => {
const conProd = new cProd(req.body.cProd);
await conProd.save();
res.redirect(`/cProds/${cProd._id}`)
});
app.get('/cProds/:id', async (req, res) => {
const conProd = await cProd.findById(req.params.id)
res.render('cProds/show', {conProd})
});
app.listen(3000, () => {
console.log('Serving on port #')
})
The app.post above seems to work when I do a simple res.send(req.body), but I get this error if I finish the code.
Dumb question, is it possibly due to not installing UUID? I don't believe I have yet.
Please help - complete beginner here who has exhausted research and figuring this out.
UPDATE: Schema and Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const opts = {toJSON:{virtuals:true}};
const CProdSchema = new Schema({
product_name: String,
type: String,
description: String
}, opts);
CProdSchema.virtual('properties.popUpMarkup').get(function() {
return `
<strong>${this.product_name}</strong>
<p>${this.description.substring(0,20)}...</p>`
});
module.exports = mongoose.model('cProd', CProdSchema)
Ah, I think I was blind.
Your problem method:
app.post('/cProds', async (req, res) => {
const conProd = new cProd(req.body.cProd);
await conProd.save();
res.redirect(`/cProds/${cProd._id}`)
});
You want to send the user to the url for the newly created cProd. But cProd is the model name, while conProd is the new document created.
Simply change the last line:
res.redirect(`/cProds/${conProd._id}`)
To avoid the confusion in future, I recommend sticking to capitalized first letter of models. I'm making a guess at the name, so for example:
const CampgroundProduct = require('./models/cProd');
And any instances (documents) of this model can be called campgroundProduct or simply product.
As to how that specific error code happened, I'm guessing that model._id references the creator for that type of field, which would be mongoose.Types.ObjectId()

I am trying to store my node rest api data to mongodb atlas. But getting insertion errors

I am trying to register the user to mongodb atlas for registration and login but i am geting an error 404.
here is full link to mycode
https://github.com/badrinathareddyr/falcon.git
server.js file
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const authRoute = require('../backend/routes/auth')
//connect to database
dotenv.config({ path: __dirname + '/.env' });
mongoose.connect(
process.env[DB_CONNECT], { useNewUrlParser: true }, () =>
console.log('connected to db!')
);
//Middleware
app.use(express.json());
//middlewareroutes
app.use('/register', authRoute);
app.listen(3000, () => console.log('server up and running'));
auth.js file
var express = require('express');
const router = express.Router();
const User = require('../models/User');
const bcrypt = require('bcryptjs');
router.post('/register', function (req, res) {
if (!req.body.email || !req.body.password) {
res.json({ success: false, msg: 'Please pass email and password.' });
} else {
var newUser = new User({
email: req.body.email,
password: req.body.password
});
// save the user
newUser.save(function (err) {
if (err) {
return res.json({ success: false, msg: 'Email already exists.' });
}
res.json({ success: true, msg: 'Successful created new user.' });
});
}
});
module.exports = router;
It's because of process.env.DB_CONNECT in your code is undefined. Change line 5 of your src/backend/server.js file like below:
const dotenv = require('dotenv').config({ path: __dirname + '/.env' });
then comment dotenv.config()
and copy .env to src/backend/.
Or change line 10 or the file like this:
dotenv.config({ path: __dirname + '/.env' });
You have const User = require('../models/User'); two time in backend/routes/auth.js. Comment line 9. It will give you error.
I fixed it and created pull request in github. Merge it.

Unhandled Promise Rejection Warning -- MERN

I'm currently working on a MERN app that takes information from a user within input fields and displays them back. I am getting this error after the onSubmit is fired:
> (node:18820) UnhandledPromiseRejectionWarning: ValidationError:
item validation failed: brand: Path `brand` is required., trailer_type:
Path `trailer_type` is required.
Model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ItemSchema = new Schema({
brand: {
type: String,
required: true
},
trailer_type: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
Router
const express = require('express');
const router = express.Router();
const auth = require('../../middleware/auth');
var bodyParser = require('body-parser');
// Item Model
const Item = require('../../models/Item');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.post('/', auth, (req, res) => {
const newItem = new Item({
brand: req.body.brand,
trailer_type: req.body.trailer_type,
date: req.body.date
});
newItem.save()
.then(item => res.json(item));
});
I've searched in several different places for someone having a similar issue, but have not had no success with implementing other's solutions.
Any help would be greatly appreciated!

Unable to fetch data from mongodb using expressjs

const express = require('express');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const app = express();
const cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
const MongoClient = mongodb.MongoClient;
const url = "mongodb://localhost:27017/recart";
app.get("/", (req, res) => {
MongoClient.connect(url,{ useNewUrlParser: true }, async (err, db) => {
if (err) throw err;
var dbo = db.db("recart");
var result = await dbo.collection("users").find()
res.json(result.data)
});
})
app.listen(3001, ()=> {
console.log('App is running on port 3001');
})
Here I am trying to fetch data from mongodb using expressjs,
but in my browser nothing is coming.
No data is coming. But in my database there are documents.
Please have a look
const url = "mongodb://localhost:27017/recart";
Do you really need to provide collection's name here?
You can try:
const mongoUrl = 'mongodb://localhost:27017/'
const MongoClient = require('mongodb').MongoClient
app.get('/', async (req, res) => {
const client = await MongoClient.connect(mongoUrl, {
useNewUrlParser: true
})
const db = client.db("database_name")
const data = await db.collection("collection_name").find().toArray()
res.json(data)
}),