Best way to store code snippets in MongoDB from Express? - node.js

I am making a code snippet web app. Basically you can upload snippets and organize them, etc. I am having trouble deciding how to store the code.
Currently, I am using express to create an API to connect to the frontend. I am inserting whatever code was inputted in the textarea, and saving it in plaintext to mongodb.
let snippet = new Snippet({
title: req.body.title,
code: req.body.code,
creator: req.body.creator,
createdDate: date,
updatedDate: date,
collections: req.body.collections,
});
await snippet.save((error, Snippet) => {
if (error) {
console.log(
"postSnippet(): Failed to save snippet to database. Error: " +
error
);
return res
.status(500)
.json({ message: "Failed to save snippet to database" });
} else {
console.log("postSnippet(): Snippet created.");
return res
.status(201)
.json({ message: "Snippet created", snippet });
}
});
When I paste the code on the UI frontend, it displays just fine. But for some reason, when I try to get the raw code in a seperate file, all the line breaks dont work.
export const fetchRawSnippet = async (req, res) => {
let snippetUrl = req.params.slug;
if (snippetUrl) {
try {
const fetchSnippets = await Snippet.findOne({ slug: snippetUrl });
if (fetchSnippets) {
res.send(fetchSnippets.code);
return res.status(200).json(fetchSnippets.code);
} else {
return res
.status(404)
.json({ message: "Could not find snippet" });
}
} catch (e) {}
} else {
return res.status(404).json({ message: "slug not provided" });
}
};
I am wondering if its a better idea to use GitHub Gists API to host the snippets...
Im not sure. Can someone just guide me in the right direction about the best way to go about code storage.

Related

deleteMany only returns 1 value deleted in change streams

I have a deleteMany request but I am having a hard time in filtering my context of the deleteMany returned value. It only returns 1 value deleted from pusherjs.
Here is my change stream code and pusher code in server side;
if (schedules.operationType === 'delete') {
const scheduleDetails = schedules.documentKey;
pusher.trigger('schedules', 'deleted', {
_id: scheduleDetails._id,
teamOne: scheduleDetails.teamOne,
teamTwo: scheduleDetails.teamTwo,
user: scheduleDetails.user,
isDone: scheduleDetails.isDone,
isStarted: scheduleDetails.isStarted,
date: scheduleDetails.date,
gameEvent: scheduleDetails.gameEvent,
});
}
Here is my pusher code in client side. I am using React by the way. It is stored in my context api;
ScheduleChannel.bind('deleted', ({ deletedSchedule }) => {
console.log(deletedSchedule);
setScheduleList(
scheduleList.filter((schedule) => schedule._id !== deletedSchedule._id)
);
});
here is my code on request;
exports.deleteallmatch = async (req, res) => {
try {
const { sub } = req.user;
const deletedMatches = await Schedule.deleteMany({ user: sub });
return res.status(201).json({
message: 'All of your schedule is successfully deleted!',
deletedMatches,
});
} catch (err) {
return res.status(400).json({
message: 'Something went wrong.',
});
}
};
The delete request is fine but I want to have realtime in my app. Cuz it happened that only one data is being send instead of many. How can I solve this?
The deleteMany() method returns an object that contains three fields:
n – number of matched documents
ok – 1 if the operation was successful
deletedCount – number of deleted documents
What you can do is:
First find all elements that match your query
Store them in some variable
Perform deleting
Return the stored variable
let deleted_items = await Schedule.find({ user: sub });
await Schedule.deleteMany({ user: sub });
return res.status(201).json({
message: 'All of your schedule is successfully deleted!',
deleted_items,
});

Reading data from mongodb using sails js removes all collection data, why?

I have a sails js app,
The following codes works fine:
list: async(req, res) => {
Data.find({}).exec((err, data)=>{
if(err){
res.send(500, {message: 'db error'});
}
res.status(200).json({
message: 'Data List',
data: data
});
});
Outputs all the data of the collection correctly.
While the below code removes all the data from the mongo db collection and then shows a empty array:
list: async(req, res) => {
const data = await Data.find({});
if(!data){
res.send(500, {message: 'db error'});
}
res.status(200).json({
message: 'Data List',
data: data
});
}
I do not understand why so, I am more comfortable with async await also it makes code look cleaner hence I wanted to use the below method. Please help how can I make the below code snippet to work just like the above one.
It worked fine, when used
const data = await Data.find();
instead of
const data = await Data.find({});

What return value of sequelize when update?

I am write API in expressjs with Sequence. But I got problem with return value when update!
I follow a tutorial on internet but it got error when num=[1] not num=1 although updating success!
exports.update = (req, res) => {
const { id } = req.params;
Post.update(req.body, {
where: { id }
})
.then((num) => {
if (num === 1) {
res.send({
message: 'Post was updated successfully.'
});
}
else {
res.send({
message: `Cannot update Post with id=${id}. Maybe Post was not found or req.body is empty!`
});
}
})
.catch((err) => {
res.status(500).send({
message: `Error updating Post with id=${id}`
});
});
};
So, what return value after call update method? and how do I solve it? Thanks.
The sequelize document of update is
public static async update(values: object, options: object): Promise<Array<number, number>>
Promise<Array<number, number>>
The promise returns an array with one or two elements. The first element is always the number of affected rows, while the second element is the actual affected rows (only supported in postgres with options.returning true).
So, it will not return only the number. you need to follow the document.
To resolve
.then((nums) => {
const num = nums[0]
.....

Perform side effects for mongoose/mongodb query

I need to query my database for users based on an array of emails and then execute a function for each result, I do this with eachAsync:
mongoose.model('User')
.find({email: {$in: ['foo#bar.com', 'bar#foo.com']}})
/* -- Run side effects before continuing -- */
.cursor()
.eachAsync((doc) => {
// do stuff
});
The problem I'm having is that I need to return a 404 status if any of the users with the given emails do not exist.
I've been looking through the mongoose docs but I can't seem to find a way of running "side effects" when working with queries. Simply "resolving" the DocumentQuery with .then doesn't work since you can't turn it into a cursor afterwards.
How can I achieve this?
You could try implementing it as shown below. I hope it helps.
// Function using async/await
getCursor: async (_, res) => {
try {
const result = []; // To hold result of cursor
const searchArray = ['foo#bar.com', 'bar#foo.com'];
let hasError = false; // to track error when email from find isn't in the array
const cursor = await mongoose.model('User').find({ email: { $in: searchArray } }).cursor();
// NOTE: Use cursor.on('data') to read the stream of data passed
cursor.on('data', (cursorChunk) => {
// NOTE: Run your side effect before continuing
if (searchArray.indexOf(cursorChunk.email) === -1) {
hasError = true;
res.status(404).json({ message: 'Resource not found!' });
} else {
// Note: Push chunk to result array if you need it
result.push(cursorChunk);
}
});
// NOTE: listen to the cursor.on('end')
cursor.on('end', () => {
// Do stuff or return result to client
if (!hasError) {
res.status(200).json({ result, success: true });
}
});
} catch (error) {
// Do error log and/or return to client
res.status(404).json({ error, message: 'Resource not found!' });
}
}

Issues working on SailsJS WebSocket

I'm getting response in
io.socket.on('chats', function (e, v) {
console.log(e)
});
when using the code block bellow.
io.socket.get('/chats', function (e, s) {
console.log(e);
});
So, main setup are okay. Then I tried to customize a bit. I wanted to pass room id to get messages from specific room instead of fetching unnecessary messages. But no response on new item addition when using
io.socket.get('/chats/get?room=PJ1RcnwbBxsH3xZn', function (e, s) {
console.log(e);
});
However that was able to fetch initial data properly as used return res.json(chats); in ChatsController.get
From ChatControllers.js
module.exports = {
get: function (req, res) {
if(!req.session.authenticated){
return res.json({error: true, message: 'You must be logged in to join chat.'})
}
if (!req.isSocket) {
return res.json({error: true, message: 'Inappropriate request format'})
}
sails.log(req.param('room'));
if(!req.param('room')){
return res.json({error: true, message: 'Inappropriate room ID'})
}
Chats.find({room: req.param('room')}).populate('user').exec(function (err, chats) {
if (err) {
return res.serverError(err);
}
Chats.subscribe(req, _.pluck(chats, 'id'));
return res.json(chats);
});
},
.....
I've added Chats.subscribe(req, _.pluck(chats, 'id')); to subscribe.
Cannot understand what I've missed in get action. I searched but didn't get good tutorial. So exploring documentation, I tried those. Can you advice to fix the issue?
Thanks
I found solution after more research. sails.sockets.join() and sails.sockets.broadcast() was my toy.
Thanks however.

Resources