So I am writing a json file, and when i write 2 users to a file, user B replaces user A
It should be:
{
"user": {
"user": "user1",
"id": "id"
},
"user": {
"user": "user2",
"id": "id2"
}
}
But Instead it just replaces user1 with user2.
Code:
if(command === "add"){
let mentionedUser = message.mentions.users.first()
var user = mentionedUser.username
var jsonData = {
users:{
user: user,
id: mentionedUser.id
}
}
fs.writeFileSync("./config.json", JSON.stringify(jsonData, null, 4), err => {
if(err) throw err;
message.channel.send("ID Pushed")
})
The default mode of fs.writeFileSync is to overwrite the complete file. You can use appendFileSync or you set an option in fileWriteSync to append the new text:
fs.writeFileSync('config.json', JSON.stringify(jsonData, null, 4), {flag: 'a'}, err => {...});
fs.appendFileSync('config.json', JSON.stringify(jsonData, null, 4), err => {...});
You can do it also asynchronously with appendFile or fileWrite. There is also a nice StackOverflow Question.
EDIT:
You can also import the file. Then you can create the object and attach it to the data structure. At the end you can write the result back to the file.
Related
I want to get nested JSON from SQLite database with NodeJS.
I did
app.get("/api/orders", (req, res, next) => {
var sql = `SELECT json_object('number', o.number
,'orderType', o.orderType
,'paymentType', o.paymentType
,'isPaid', o.isPaid
,'isReady', o.isReady
,'isProgress', o.isProgress
,'isCanceled', o.isCanceled
,'isDelivered', o.isDelivered
,'createdAt', o.createdAt
,'updatedAt', o.updatedAt
,'orderItems',
(SELECT json_group_array(json_object('id', ot.itemID,
'name', ot.itemName,
'quantity', ot.quantity))
FROM orderItems AS ot WHERE ot.orderID = o.number)) AS 'order'
FROM orders AS o`;
db.all(sql, [], function (err, result) {
if (err) {
res.status(400).json({"error" : err.message});
return;
}
res.send(result)
});
});
but I get this
[
{
"order": "{\"number\":1,\"orderType\":\"Take out\",\"paymentType\":\"At counter\",\"isPaid\":0,\"isReady\":0,\"isProgress\":0,\"isCanceled\":1,\"isDelivered\":0,\"createdAt\":\"10/25/2021 15:34:48\",\"updatedAt\":\"10/25/2021 17:19:2\",\"orderItems\":[{\"id\":2,\"name\":\"Chicken Wings\",\"quantity\":1},{\"id\":6,\"name\":\"Saltado Shaken Fries\",\"quantity\":1},{\"id\":7,\"name\":\"Steam rice\",\"quantity\":1}]}"
},
{
"order": "{\"number\":2,\"orderType\":\"Dine in\",\"paymentType\":\"Pay here\",\"isPaid\":1,\"isReady\":0,\"isProgress\":1,\"isCanceled\":0,\"isDelivered\":0,\"createdAt\":\"10/25/2021 15:35:59\",\"updatedAt\":\"10/25/2021 15:35:59\",\"orderItems\":[{\"id\":1,\"name\":\"Fam's Salad\",\"quantity\":2},{\"id\":2,\"name\":\"Chicken Wings\",\"quantity\":2},{\"id\":8,\"name\":\"Vietnamese Coffee\",\"quantity\":1}]}"
},
{
"order": "{\"number\":3,\"orderType\":\"Dine in\",\"paymentType\":\"At counter\",\"isPaid\":0,\"isReady\":0,\"isProgress\":1,\"isCanceled\":0,\"isDelivered\":0,\"createdAt\":\"10/25/2021 15:44:48\",\"updatedAt\":\"10/25/2021 15:44:48\",\"orderItems\":[{\"id\":8,\"name\":\"Vietnamese Coffee\",\"quantity\":1},{\"id\":15,\"name\":\"Soft Drink: Coke\",\"quantity\":1}]}"
}
]
It returns weird format keys like \"number\", \"orderType\"
Is there any way that I can get a nicer JSON in this case?
Thank you
{
"_id": {
"$oid": "5a2de0a00d6baa43e8b925d0"
},
"name": "test",
"playList": [
{
"url": "https://p.scdn.co/mp3-preview/8aa799e60164f8a1fb311188d9d85ef65d7782c6?cid=ed36a056ee504173a3889b2e55cbd461",
"artist": "Kenny G",
"songName": "My Heart Will Go On (Love Theme from \"Titanic\")",
"_id": {
"$oid": "5a2de0ad0d6baa43e8b925d1"
}
},
{
"url": "https://p.scdn.co/mp3-preview/7c49854f18e6dfda6cd97ab5e8bc139d7ca82b7c?cid=ed36a056ee504173a3889b2e55cbd461",
"artist": "PRODUCE 101",
"songName": "PICK ME",
"_id": {
"$oid": "5a2de13b0d6baa43e8b925d2"
}
}
],
"__v": 0
}
I have a database called channels where each channels contain a playList as shown below. I want to delete a single item when a button is clicked. I can handle the onClick event part, but I am not sure how to implement the routes part.
I know that I start by doing something like
router.delete(''/channels/:id', function(req, res){
something here...
})
but how can I access a particular item (probably with a unique id?) and delete it from the DB?
EDIT
By using the GET below
router.get('/channels/:id',
isLoggedIn,
function(req, res) {
channel.findOne({'name':req.params.id},function(err,channeldata){
if(err || channeldata === null){
res.status(404).send({
message: 'Channel Not Found',
data: []
})
}
else {
res.status(200).json({
message: "channel to "+req.params.id+"success",
data:channeldata
})
}
})
});
I get the data for a single channel in my DB.
But since I am new to this stuff, I am not sure how to access each item of the playList and delete a single data.
EDIT2
var mongoose = require('mongoose');
var ChannelSchema = new mongoose.Schema({
name: {type:String,required:true},
playList: [{
songName: { type : String },
artist: { type : String },
url: { type : String }
}]
})
module.exports = mongoose.model('Channel',ChannelSchema);
You can try the following snippet that contains the DELETE (part of CRUD) endpoint for your resource collection (i.e. the channels):
router.delete('/channels/playlist/song', isLoggedIn, (req, res) => {
const channel_id = req.query.channelId;
const song_id = req.query.songId;
// the following query deletes a song form a playlist of a certain channel
channel.update({_id: ObjectId(channel_id)},{$pull:{playList:{_id:ObjectId(song_id)}}})
.exec()
.then(result => {
// for checking if document was found and deleted
// mongodb actually returns special object `result`
// which has its own certain fields
res.status(200).send({
status: "success",
message: result
});
})
.catch(error => {
// here we see if we had any problem with server or db itself
console.log(error)
res.status(500).send({
success: false,
message: "Something went wrong with DELETE /channels/:id"
})
})
});
I assume that you know what ObjectId() function does
if you do not have it declared, declare the following comment
in the beginning of the file (where you require everything)
const mongoose = require('mongoose'); // you must have this
const ObjectId = mongoose.Types.ObjectId; // gets the function
Let me know if this helps, or if you do not understand something - I will make an edit so that you get it.
I need to find the collection data by an single MongoDB query using Node.js. I am providing the collection below.
f_user_login:
{
"_id": {
"$oid": "5981b48654d471000459208e"
},
"email": "subhrajyoti.pradhan#oditeksolutions.com",
"password": "d0e49bcba946540cb3d5fc808870d16b",
"dob": "02-08-2017",
"created_date": "2017-08-02 11:16:21",
"updated_date": "2017-08-02 11:16:21",
"status": 1,
"token": "b85ff4c47093217587f8c7f2fff7ff86b1bcbf6a7321705871435929ee38",
"verification_id": ""
}
{
"_id": {
"$oid": "598aa189e5f78d00042f48ae"
},
"email": "subhrajyotipradhan#gmail.com",
"password": "d0e49bcba946540cb3d5fc808870d16b",
"dob": "1986-04-10",
"created_date": "2017-08-09 05:45:44",
"updated_date": "2017-08-09 05:45:44",
"status": 0,
"token": "",
"verification_id": "7ffbe3f9be82b2af84491d3e8dff4fa1a65f973d"
}
I am providing my code below.
exports.userSignin=function(req,res){
var email=req.body.email;//subhrajyotipradhan#gmail.com
var password=req.body.password;//d0e49bcba946540cb3d5fc808870d16b
var pass=mden(password);
if (email !='' && password !='') {
db.f_user_login.count({email:email,password:pass,status:1},function(err,docs){
if(docs > 0){
token=crypto.randomBytes(30).toString('hex');
db.f_user_login.update({email:email},{$set:{token:token}},function(err,doc){
db.f_user_login.find({email:email},function(error,docu){
var edata=[{"email": docu[0].email,"dob": docu[0].dob,"created_date":docu[0].created_date ,"id": docu[0]._id,"updated_date":docu[0].updated_date,"token_id":token}];
var data={"statusCode": 200,"data":edata,"message": "The user logged successfully."};
res.send(data);
})
})
}else{
console.log(email,password);
db.f_user_login.find({$or:[{email:email},{password:pass},{status:1}]},function(err,getdocs){
if (!err) {
var uemail=getdocs[0].email;
var upass=getdocs[0].password;
var ustatus=getdocs[0].status;
console.log('email,pass,status',uemail,upass,ustatus);
if (uemail != email) {
var data={"statusCode": 401,"error": "Unauthorized","message": "Invalid email id .Please provide a valid email id"};
}
if (upass != pass) {
var data={"statusCode": 401,"error": "Unauthorized","message": "Invalid Password .Please provide a valid Password"};
}
if (ustatus == 0) {
var data={"statusCode": 401,"error": "Unauthorized","message": "you have not verified your account using the link sent to your email."};
}
res.send(data);
}
})
}
})
}
}
Here my input email and password is right and I need to check the status and get this you have not verified your account using the link sent to your email. message. But unfortunately both document has same password its always checking the first document but originally I need to check the second document for validation.
It is possible using 3 three different query but here I want to operate a single query. Is this possible?
You can use below code for the entire process:
Note: Some typos or code may need to be changed. But you can use the basic idea.
if (email !='' && password !='') {
console.log(email,password);
db.f_user_login.find({$and:[{email:email},{password:pass}]},function(err,getdocs){
if (!err && /*check if the getdocs is not empty*/) {
var uemail=getdocs[0].email;
var upass=getdocs[0].password;
var ustatus=getdocs[0].status;
// update your collection from here with ID
// Remember update is work fine with id
console.log('email,pass,status',uemail,upass,ustatus);
if (ustatus === 0) {
var data={"statusCode": 401,"error": "Unauthorized","message": "you have not verified your account using the link sent to your email."};
}else if(ustatus === 1){
var data={"statusCode": 200,"data":edata,"message": "The user logged successfully."};
}
res.send(data);
}
})
}
I am trying to use Dynamodb on a new project and i have to say i am very confused.
So i have setup a new table with a hash key called ID which i am setting as a timestamp as it needs to be unique.
I am then inserting my data as follow with Lambda
var tableName = "TrackerTable";
var datetime = new Date().getTime().toString();
var putData = {
"TableName": tableName,
"Item": {
"ID" : {
"N": datetime
},
"TrackIt": {
"S": event.trackit
},
"Latitude": {
"N": event.lat
},
"Longitude": {
"N": event.lon
},
"Time": {
"N": datetime
}
}
}
dynamoDB.putItem(putData, function(err, data) {
if (err) {
context.fail('ERROR: Dynamo failed: ' + err);
} else {
console.log('Dynamo Success: ' + JSON.stringify(data, null, ' '));
context.succeed('SUCCESS');
}
});
So my table starts to look like this which is fine.
So i am trying to use Lambda to return my results based on the trackit column?
I have the following code which doesnt work.
var tableName = "TrackerTable";
var datetime = new Date().getTime().toString();
var queryData = {
"TableName": tableName,
"ConsistentRead": true,
"KeyConditionExpression": "trackit = :val",
"ExpressionAttributeValues": {":val": {"S": "05LUGFr7494"}}
};
dynamoDB.query(queryData, function(err, data) {
if (err) {
context.fail('ERROR: Dynamo failed: ' + err);
}else{
console.log('Dynamo Success: ' + JSON.stringify(data, null, ' '));
context.done(null, data.Items);
}
});
I get this error.
{
"errorMessage": "ERROR: Dynamo failed: ValidationException: Query condition missed key schema element: ID"
}
How can i query all the trackit values i cant add the ID value as it will only return one value?
Very confused.
The way you have your table setup I think you'll need to do a scan here instead of a query[1]. If this is an operation that your will be doing frequently and want to have the ability to do a query, you would need to add the trackit property as one of your secondary indexes.
[1] http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html
I have tried a lot of different ways but maybe I dont have the hang of the way mongodb needs me to query it.
this is what the doc looks like.
{
"username" : "amitverma",
"notifications" : {
"notification_add_user" : [
{
"sender" : "a",
"action" : "b",
"type" : "c",
"objectType" : "d",
"objectUrl" : "e"
}
]
},
"_id" : ObjectId("539aa673e97933e7a5000001")
}
I want to remove the object inside "notification_add_user". And these are the different ways I have tried to get it working.
db.notifications.update(
{'username': 'amitverma' },
{ $pull: {
"notifications.notification_add_user":{'sender': "a"}
}}
)
This works in console.
But the code that I have written for it doesnt get the job done.
// notificationtype is 'add_user'
removequery['notifications.notification_' + notificationtype] = { 'sender': 'a' };
co_notifications.update(
{'username': data.username},
{$pull : removequery}, function(err, docs){
console.log('remove notification callback')
console.log(err)
console.log(docs)
})
)
Using the native MongoDB driver, I have used the following query to update from a node console and it works:
>MongoClient = require('mongodb').MongoClient;
>format=require('util').format;
>MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('notifications');
collection.count(function(err, count) {console.log(format("count = %s", count));});
collection.update(
{'username': 'amitverma'},
{$pull:{'notifications.notification_add_user':{'sender':'a'}}},{w:1},function(err){
if (err) console.warn(err.message);
else console.log('successfully updated');
})
})
db.notifications.find({'username': 'amitverma' }).forEach( function(result) {
var i;
for(i in result.notifications.notification_add_user) {
var sender = result.notifications.notification_add_user[i]['sender'];
if(sender === 'a') {
delete result.notifications.notification_add_user[i]['sender'];
}
}
db.notifications.save(result);
});
First i will get all the results where the username is equal to
'amitverma'
Then i loop through the notification_add_user array and see if sender is equal to 'a' and delete all the match results
And for last i save the changes