Thanks a lot! i appreciate.
Hey Guys, I have successfully connected to mogoDB for the listingsā¦ I am able to post and get listings by user, working on getting the users post and get working as well. I will post a tutorial article / video when I am done with it
I am also working on my own app extended off this tutorial with connection to MongoDB - I am currently able to get and post listingsā¦ working on functionality with the DB for user auth
This is how I did it in backend/listings.js
include mongoDB files
var MongoClient = require('mongodb').MongoClient;
var mongo = require('mongodb');
var url = "mongodb+srv://yourname:password@cluster0.v1sxt.gcp.mongodb.net/yourDatabaseName?retryWrites=true&w=majority";
Here is the rest of the modified fileā¦ note I am not using the image stuff
const upload = multer({
dest: "uploads/",
limits: { fieldSize: 25 * 1024 * 1024 },
});
const schema = {
title: Joi.string().required(),
description: Joi.string().allow(""),
status: Joi.string().required(),
categoryId: Joi.number().required().min(1),
userId: Joi.string().required(),
};
const validateCategoryId = (req, res, next) => {
if (!categoriesStore.getCategory(parseInt(req.body.categoryId)))
return res.status(400).send({ error: "Invalid categoryId." });
next();
};
router.get("/", (req, res) => {
// const listings = store.getListings;
//const resources = listings.map(listingMapper);
var id = req.query.id;
console.log(id);
MongoClient.connect(url, async function (err, db) {
if (err) throw err;
var dbo = db.db("Tricklist");
// Query for a movie that has the title 'The Room'
var query = {userId: id};
var options = {
// sort matched documents in descending order by rating
// sort: { rating: -1 },
// Include only the `title` and `imdb` fields in the returned document
projection: { _id: 0, title: 1, description: 1, status: 1 },
};
listings1 = dbo.collection("tricks").find(query);
listingsArray = await listings1.toArray();
console.log(listingsArray);
res.send(listingsArray);
db.close();
});
// }).then(res.send(listingsArray));
});
router.post(
"/",
[
// Order of these middleware matters.
// "upload" should come before other "validate" because we have to handle
// multi-part form data. Once the upload middleware from multer applied,
// request.body will be populated and we can validate it. This means
// if the request is invalid, we'll end up with one or more image files
// stored in the uploads folder. We'll need to clean up this folder
// using a separate process.
// auth,
upload.array("images", config.get("maxImageCount")),
validateWith(schema),
validateCategoryId,
imageResize,
],
async (req, res) => {
const listing = {
title: req.body.title,
categoryId: parseInt(req.body.categoryId),
description: req.body.description,
status: req.body.status,
userId: req.body.userId,
};
// listing.images = req.images.map((fileName) => ({ fileName: fileName }));
// if (req.body.location) listing.location = JSON.parse(req.body.location);
//if (req.user) listing.userId = req.user.userId;
store.addListing(listing);
console.log("post called");
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Tricklist");
var myobj = listing;
dbo.collection("tricks").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
res.status(201).send(listing);
}
);
router.delete(
"/:id",function (req, res) {
var id = req.params.id;
console.log(id);
console.log("blej");
MongoClient.connect(url, function(err, db) {
var dbo = db.db("Tricklist");
dbo.collection("tricks").deleteOne({ _id: new mongo.ObjectId(id) }, function (err, results) {
if(err){
console.log(err);
}
else{
console.log(results);
}
});
});
res.json({ success: id })
}
)
module.exports = router;
2 Likes
Please can you record a video for this and send in link. Thanks