i am trying to find corder data in below documents but i can not do this work if you know about how to find nested array data in below document so please find data for {corder}.
{
"_id": "63064232cf92b07e37090e0a",
"sname": "Bombay collection ",
"phone": 9963366555,
"costomer": [
{
"cname": "Ammar ",
"cphone": 919628497,
"ccity": "Palanpur",
"_id": "632ef012a9b88eb59d0210fa",
"corder": [
{
"clothType": "Pathani",
"prize": 236,
"date": "2022-09-24",
"status": "true",
"_id": "632ef078a9b88eb59d02110c"
}
],
}
],
},
and my code is id = "main document id" & obid ="cosomer id " & orid = " order id "
app.get('/getuser/:id/:obid/:orid', async (req, res) => {
try {
const id = req.params.id
const obid = req.params.obid
const orid = req.params.orid
console.log(id);
const peruserdata = await getschema.find({ 'costomer.corder': orid } ,
{ "_id": orid, "costomer.$.corder": { $elemMatch: { "_id": orid } } });
res.status(201).json(peruserdata);
} catch (error) {
console.log(error);
res.send(error)
}
})
Related
I have a mongodb collection like this:
[{
"_id": {
"$oid": "63b79f9e5c98b4aa46719920"
},
"time": {
"$numberLong": "1672978334287"
},
"tvl": 0.005495200757897796,
"wethToken1": true
},{
"_id": {
"$oid": "63b79fad5c98b4aa46719921"
},
"time": {
"$numberLong": "1672978349046"
},
"tvl": 0.010990401515795592,
"wethToken1": true
},{
"_id": {
"$oid": "63b7a0ee5c98b4aa46719922"
},
"time": {
"$numberLong": "1672978670070"
}]
I want to query the data but i want a to param (from is aways Date.now())
So i wrote this query:
const queryTVL = async (from) => {
// const formatedFrom = NumberLong(from)
// const formatedTo = NumberLong(to)
try {
const collection = await mongoClient.db("tangle-db").collection("tvl")
const documents = await collection.find({
"time": {
"$gt": from
}
}).toArray()
let docArr = []
documents.map((data) => {
console.log(data, 'data')
docArr.push({
tvl: data.tvl,
time: data.time
})
})
console.log(docArr)
return docArr
} catch (error) {
console.log(error, 'for getLastTVL')
}
}
But docArr aways return empity, something is wrong with this block:
const documents = await collection.find({
"time": {
"$gt": from
}
Can someone give me a hint?
I believe you could specify "time.$numberLong" in your find() to find the actual number.
You need to specify NumberLong to the integer as used while inserting it:
db.collection.find({
"time": {
"$gt": NumberLong("1672978349046")
}
})
I have a source.json file, and then another file of changes which I parse, and need to write out the array back to the source file. Here is the source.json structure:
{
"users" : [
{
"id" : "1",
"name" : "Albin Jaye"
}
],
"playlists" : [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [
"8",
"32"
]
}
],
"songs": [
{
"id" : "1",
"artist": "Camila Cabello",
"title": "Never Be the Same"
}
]
}
Here is the changes.json structure. I have a CRUD like "add" directive and the "payload" which is the entry to be added to the source file:
{
"users": [{
"action": "add",
"payload": [{
"id": "1",
"name": "Albin Jaye"
},
{
"id": "2",
"name": "Dave Mustaine"
}
]
}],
"playlist": [{
"action": "add",
"payload": [{
"id": "1",
"owner_id": "2",
"song_ids": [
"8",
"32"
]
}]
}],
"songs": [{
"action": "add",
"payload": [{
"id": "1",
"artist": "Camila Cabello",
"title": "Never Be the Same"
}]
}]
}
I have written this code in Node to read in the source file and parse and then read in the changes file. Once the changes file is read, I iterate over and see what "CRUD" directive is there. When I find "add", I then push the payload to an array. After I get finished, when I console log out I get this:
[
[ 'users', '[object Object],[object Object]' ],
[ 'playlists', '[object Object]' ],
[ 'songs', '[object Object]' ]
]
This is swell. BUT, I need now to take this result and Stringify it I think and place it back into the source JSON file in the appropriate place. I think it will be some type of ```fs.appendFile()`` function, but not sure. Here is my code so far:
// Stream in source file
fs.readFile('./' + inputFile, (err, data) => {
if (err) throw err;
let input = JSON.parse(data);
//console.log(input);
});
// Stream in changes file
fs.readFile('./' + changesFile, 'utf-8', (err, jsonString) => {
if (err) {
console.log(err);
} else {
try {
const data = JSON.parse(jsonString);
const array = [];
Object.entries(data).map(([key, [{ action, payload }]]) => {
switch (key) {
case 'users': {
if (action === 'add') {
console.log("it's an add");
array.push([`${key}`, `${payload}`]);
}
break;
}
case 'playlists': {
if (action === 'add') {
console.log("it's an add");
array.push([`${key}`, `${payload}`]);
}
break;
}
case 'songs': {
if (action === 'add') {
console.log("it's an add");
array.push([`${key}`, `${payload}`]);
}
break;
}
}
});
console.log(array);
} catch (err) {
console.log('Error parsing JSON', err);
}
}
});
// after we have merged changes and source we need to write out
// Don't know how to merge the changes array I created above back into the
// source.json file?
fs.appendFile('./' + outputFile, JSON.stringify(array, null, 2), err => {
if (err) {
console.log(err);
} else {
console.log('File sucessfully written');
}
});
I'm not 100% sure where you're going with your implementation, but I think a better way to go about this would be to update the original data object with the changes, and then write the changes out to a file:
const data = JSON.parse(fs.readFileSync(inputFile));
const changes = JSON.parse(fs.readFileSync(changesFile));
for(const [table, actions] of Object.entries(changes)){
if(!(table in data))continue;
for(const actionDetail of actions){
if(actionDetail.action === 'add'){
data[table].push(...actionDetail.payload);
}
}
}
fs.writeFileSync(inputFile, JSON.stringify(data));
I'm trying to retrieve documents matching an id through a simple SQL query in my JavaScript stored procedure. But it always returns that no document matches the id found. Tried all the things available in the Microsoft Documentation and the other StackOverflow answers. Here is my function:
function updateDocument () {
let context = getContext();
let collection = context.getCollection();
let collectionLink = collection.getSelfLink();
let response = context.getResponse();
tryQueryAndUpdate();
function tryQueryAndUpdate () {
var filterQuery = 'select * from user r WHERE r.id = "f5eddf33-7826-40c3-a634-9c349e5c7f73"';
let isAccepted = collection.queryDocuments(collectionLink, filterQuery, {}, function (err, documents, responseOptions) {
if (err) throw err;
if (documents.length > 0) {
console.log("Documents exists - " + documents.length);
} else {
// Else a document with the given id does not exist..
console.log("Document doesn't exist " + documents.length);
}
});
}
}
My document:
{
"firstName": "firstname",
"lastName": "lastname",
"email": "firstname.lastname#gmail.com",
"businessRole": "",
"functionalArea": null,
"type": "internal",
"status": "enable",
"modifiedDate": "2020-07-10T14:34:54.557Z",
"id": "f5eddf33-7826-40c3-a634-9c349e5c7f73",
"_rid": "H+pKAKZdGd0BAAAAAAAAAA==",
"_self": "dbs/H+pKAA==/colls/H+pKAKZdGd0=/docs/H+pKAKZdGd0BAAAAAAAAAA==/",
"_etag": "\"730103dd-0000-0100-0000-5f6302800000\"",
"_attachments": "attachments/",
"securityGroup": "c5d3dc10-bfa0-11ea-8394-48463089baf6",
"engagementId": "945acacf-a3ea-43ef-8e31-70576055ba4f",
"sort": {
"firstName": "firstname",
"lastName": "lastname"
},
"userStatus": "active",
"_ts": 1600324224
}
document:
container:
Any help would be appreciated. Thank you.
Execution parameters:
Console output:
So Basically, i have a JSON file which consists of user and group data. I want to delete a particular group. This is what my JSON file looks like:
authdata.json:
[{
"name": "Allan",
"role": ["Group Admin", "Super Admin"],
"group": ["Cool-Group", "ss"]
}, {
"name": "super",
"group": ["Nerd Group"],
"role": ["Super Admin"]
}, {
"name": "Terry",
"role": ["Group Admin"],
"group": ["Cool-Group"]
}, {
"name": "Kaitlyn",
"role": ["Group Admin"],
"group": ["Nerd-Group"]
}, {
"name": "Alex",
"role": ["Group Admin"],
"group": ["Cool-Group"]
}]
I'm just confused on how to handle a http delete request in nodeJS?
this how my angular component is sending the request to the server:
remove.component.ts:
RemoveGroup() {
this.httpService.delete < any > (this.apiURL + 'deletegroup', {
group: this.groups
}).subscribe(
data => {
if (data['success'] == true) {
alert(data.group + " is removed");
} else {
alert("No groups found");
}
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
}
This is the server side on NodeJS (reading the json file, assigning the data to a variable, trying to delete the group (which is not working for me) and writting back to the JSON file):
deletegroup.js:
app.delete('/api/deletegroup', (req, res) => {
// localhost:3000/api/auth?username=Terry
var groups = req.body.group;
var userObj;
fs.readFile('authdata.json', 'utf8', function(err, data) {
if (err) {
console.log(err);
//Some error happended opening the file. No Success
res.send({
'group': '',
'success': false
});
} else {
userObj = JSON.parse(data);
for (let i = 0; i < userObj.length; i++) {
for (let j = 0; i < userObj.length; j++) {
if (userObj[i].group[j] == groups) {
userObj.splice(userObj.indexOf(groups), 1);
//find first instance of user name and success
}
}
}
var newdata = JSON.stringify(userObj);
fs.writeFile('authdata.json', newdata, 'utf-8', function(err) {
if (err) throw err;
//Send response that registration was successfull.
res.send({
'group': groups,
'success': true
});
});
//no username was found that matched
}
});
});
I assume that the problem is not with HTTP DELETE request. The concern is with how to remove a child node. See the below code snippet. You can pass the groups as an array to the deleteGroup function and see the result.
var data = [{
"name": "Allan",
"role": ["Group Admin", "Super Admin"],
"group": ["Cool-Group", "ss"]
}, {
"name": "Terry",
"role": ["Group Admin"],
"group": ["Cool-Group"]
}];
function deleteGroup(groupArray) {
groupArray.map((needle)=>{
data.map((userObj) => {
if(userObj.group) {
userObj.group.map((groupName, index)=>{
if (groupName == needle){
userObj.group.splice(index)
}
});
} else {
console.log("No group present for this user.")
}
});
});
return data
}
//uncomment below line & run in console to see the results
//console.log(deleteGroup(["Cool-Group"]))
Try out directly in Jsbin - https://jsbin.com/pejidag/1/edit?js,console
Happy coding!
I have the following database structure stored in the mongoDB:
"location" : "Halifax",
"students" : [
{
"name": "Mike",
"ID": "B00123456",
"images": [
{
"image_url":"",
"image_id":""
}
]
},
{
"name": "Rinan",
"ID": "B00999999",
"images": [
{
"image_url":"",
"image_id":""
}
]
}
]
My question is: how do I push a new object to images array inside a student named Mike who has an ID of "B00123456", I know I should use mongoDB's update and set method. But I just couldn't find a way to achieve that. The result I want is:
"location" : "Halifax",
"students" : [
{
"name": "Mike",
"ID": "B00123456",
"images": [
{
"image_url":"",
"image_id":""
},
{
"image_url":"www.example.com",
"image_id":"uqxhqbxqx_1219"
}
]
},
{
"name": "Rinan",
"ID": "B00999999",
"images": [
{
"image_url":"",
"image_id":""
}
]
}
]
Below is what I am trying using MongoDB's update and set:
// Connect and create a new doc
MongoClient.connect('mongodb://username:password#iad1- mongos0.objectrocket.com:someNode/db_name', functionb(err, db) {
if (err) {
console.dir(err);
console.log("error connected to mongodb");
} else {
var collection = db.collection('student_info_collection');
var student_name = req.body.name;
var student_id = req.body.ID;
collection.update(
{ location:"Halifax" },
{ ID:student_id}
{ name: student_name},
{$push: {
{
"images": [
{
"image_url":"www.example.com",
"image_id":"uqxhqbxqx_1219"
}
]
}
}
}, function(err,result){
if (err)
console.log("Something's wrong");
else
res.sendStatus(200);
}
);
}
});
Any help?
The update() function is
update(selector, document[, options][, callback])
The first parameter is selector, please try this one
var student_name = req.body.name;
var student_id = req.body.ID;
collection.update(
{ location:"Halifax",
'students.ID': student_id,
'students.name': student_name},
{$push: { "students.$.images":
{
"image_url":"www.example.com",
"image_id":"uqxhqbxqx_1219"
}
}
}, function(err,result){