I am using node.js to export a collection that I have in firestore.
Until now the connection and the selection of the documents of the collection work perfectly.
I am trying to save the structure in a json file but the result is not what I expected.
This is the output in the physical file:
enter image description here
On the right of the photo, it will be seen as presented by the console.log and on the right it is displayed as recorded by json.push
I can't get the physical file to have the structure shown in the console.log.
I appreciate all your help.
as you will see the structure here is failing: "USBCALI|AFILIADO|uqcMSoxdwCTQoLzS2J6brNTZ3Dy2",
":",
{.....
should be: USBCALI|AFILIADO|uqcMSoxdwCTQoLzS2J6brNTZ3Dy2 : {.....
this is the code
const jsonfile = require('jsonfile')
function start (db, file, collection) {
const ref = db.collection(collection)
const json = []
console.log(`Getting ${collection}...`)
ref
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.id, ':', doc.data())
json.push(doc.id, ':', doc.data())
})
console.log(`Writing ${file}...`)
jsonfile.writeFile(file, json, {spaces: 2}, err => {
if (err) {
console.error(err)
} else {
console.log(`Collection ${collection} successfully written to ${file}.`)
}
})
})
.catch((err) => {
console.log('Error getting documents', err)
})
}
module.exports = start
Let me explain whats going on here
console.log(doc.id, ':', doc.data())
Is logging out the information how you would think you would like it to be
json.push(doc.id, ':', doc.data()) is pushing 3 elements into the array every time its called.
What you really want to do is manipulate the data properly into an object using a map function. I'm making some assumptions based on all the info I have here, but I'm guessing you want to do something like
var docs snapshot.map( doc => ({[doc.id] : doc.data()})
json.push(docs)
instead of
snapshot.forEach((doc) => {
console.log(doc.id, ':', doc.data())
json.push(doc.id, ':', doc.data())
})
You could also do (this is a bit more verbose than the map method but will essentially do the same thing. The map function is like select in sql or Linq, its handy to transform data from one form into another 😀
snapshot.forEach((doc) => {
var currentItem = {[doc.id] : doc.data()}
json.push(currentItem)
})
Since you have used some es6 notation, I'm assuming that Computed Property Names are supports, if not let me know and Ill come up with another soloution
Related
onMounted(() => {
productService.value
.getProducts()
.then((data) => (products.value = data));
console.log((products))
});
When I print products with console.log, here what I have.
capture of the console
I see that the data I want are in RawValue but I don't know how to access them.
I tried Object.values(products) or just console.log(products._rawValue) or console.log(products.rawValue) it print undefined.
Do you know what function call ?
Thanks
There are 2 issues
#1 - you're using console.log(products) which shows you the reactive object, what you need instead is console.log(products.value) which will only show the value, which should match the content of data.produtcs
#2 - you might find that 👆 now shows an empty result. The reason that's happening is that you're calling the console log after the async function, but before it finishes, so you're calling it before it has a chance to update. To fix that, you can log as part of the async function
onMounted(() => {
productService.value
.getProducts()
.then((data) => {
products.value = data;
console.log(products.value);
})
});
If you're using the products inside a template, you don't need to worry about what's before or after the async function since it will re-render the component on change.
Also, you probably don't need to define productService as a ref, the class is likely not something that needs to be reactive, so you can just do simple assignment and then skip the .value to call getProducts
with axios what I do is take out the data with response.data you could try
onMounted(() => {
productService.value.getProducts().then((response) => (
products = response.data
));
console.log(products.length);
});
I'm using knex with MYSQL. I have a function that I called to show the data to the user, Also I'm using a view table which has 5 right join on it and I think it will take some time to return values from the table plus I added the WHERE condition on my knex and it looks like this :
var showClass = (teacherId , ClassId){
return new Promise((resolve , reject)=>{
knex.select().from('v_cardex_details').where({teacherId }).andWhere({id : ClassId}).then(classes =>{
resolve(classes)
}).catch(err=>{
console.error(`Show Teacher class Error: ${err}`)
reject (err)
})
})
}
and I call this general function to response some request something like this
exports.EditClass = (req,res)=>{
knex('Table').update({//Some update stuff here}).then(()=>{
showClass(req.user.id, req.params.id).then(data=>{
return res.status(200).json({data , message:''})
})
}).catch()
}
With the same input, this function after updating returns value and some times it returns an empty string, especially when it's on the hosting server most of the time it returns nothing but { message : '' }
Try to create simplified code by removing all the unnecessary wrappers and you might find where your problem is. AFAIK there is no way that that your {data , message:''} would create an object containing just {message: ''} without any additional attributes.
> var data = []
undefined
> {data, foo:1}
{ data: [], foo: 1 }
> data = undefined
undefined
> {data, foo:1}
{ data: undefined, foo: 1 }
> {data1, foo:1}
ReferenceError: data1 is not defined
The problem you are experiencing does not exist in from the code you have shared (though there are syntax errors and other problems).
EDIT:
res.json() uses JSON.stringify() to convert js object to JSON strings. So if value of data in your code is undefined instead of and array, that could explain the behavior you are experiencing:
λ node
> JSON.stringify({ test: undefined })
'{}'
As you can see JSON.stringify() omits the attributes with value undefined from the output JSON string.
I am quite new to React Native and JS and have recently purchased a React Native template which has a Dummy DB.
Ideally Id like it to pull data from an external JSON (api) which is being generated from a PHP website we already have running.
Here is the Dummy data file:
import {
DoctorModel,
TreatmentModel,
CampaignModel,
EventModel
} from "../models";
export const doctorsList: DoctorModel[] = [ { ##JSON HERE## } ];
export const treatmentsList: TreatmentModel[] = [ { ##JSON HERE## } ];
export const campaignList: CampaignModel[] = [ { ##JSON HERE## } ];
export const eventList: EventModel[] = [ { ##JSON HERE## } ];
I want it to export as the same values as above so it will work seamlessly with the current app configuration.
I have tried the following...
export const doctorsList: DoctorModel[] = () =>
fetch(' ##LINK TO API## ')
.then((response) => response.json());
But got this error:
Type '() => Promise<any>' is missing the following properties from type 'DoctorModel[]': pop, push, concat, join, and 27 more.
I have looked all over here and other platforms for a solution but cant find anything.
Again the ideal outcome would for it to work exactly how it would if I manually typed the JSON in as seen in the first code snippet.
Any help is much appreciated, still trying to wrap my head around React! :)
This doesn’t look like a react problem, but a typescript one. Typescript does a type inference from your return value to check and see if it matches what you’ve stated.
In short: you’ve just declared your types wrong.
The function doesn’t return a DoctorModel[] it’s returning Promise<DoctorModel[]>
export const doctorsList: Promise<DoctorModel[]> = () =>
fetch(' ##LINK TO API## ')
.then((response) => response.json() as DoctorsModel[]);
So changing that line ought to make your typescript compiler chooch again!
In the following code I am getting data from server and filling array with them:
Vue.http.post('/dbdata', DataBody).then((response) => {
App.$refs.userContent.rasters_previews_list.$set(response); // putting JSON answer to Component data in userContent
console.log("App.$refs.userContent.rasters_previews_list: ", App.$refs.userContent.rasters_previews_list.length);
}, (response) => {
console.log("Error")
});
Now I am filling. data is declared in var userContent = Vue.extend({. I am using App.$refs.userContent.rasters_previews_list to set it's value, because one man from SO said that there is no other way to get access to constructor. I tried to do output of rasters_previews_list after changing with watch, but here is what I am see. http://img.ctrlv.in/img/16/08/04/57a326e39c1a4.png I really do not understand am I setting it's right way or no. If yes, why I do not see data and see only this crap?
data: function () {
return {
rasters_previews_list: []
}
}
But How I can iterate it with v-for?
<ul v-for="img in rasters_previews_list">
<li>{{img}}</li>
<ul>
This code is display one bullet. So it's look like it's assume that there is one object.
My object in browser console look like:
Object {request: Object, data: Array[10], status: 200, statusText: "OK", ok: true}
Your setting the full response instead of just the data you actually need.
Vue.http.post('/dbdata', DataBody).then((response) => {
App.$refs.userContent.rasters_previews_list.$set(response.data);
console.log("App.$refs.userContent.rasters_previews_list: ", App.$refs.userContent.rasters_previews_list.length);
}, (response) => {
console.log("Error")
});
If this isn't what you are looking for please post a full example.
I'm trying to retrieve an array of objects in mongoose using code that looks like this.
mongoPlaces
.find({
'person.types': {$in: ["student"]}
})
.select('family')
.lean()
.limit(3)
.exec(function (err, families) {
console.log()
})
the results is something like this
[
0: family:{objects}
1: family:{objects}
2: family:{objects}
]
and I need something like this
[
0: {objects}
1: {objects}
2: {objects}
]
is there some way to retrieve the contents of an object instead of the object itself using mongoose without having to make a loop and correct the array or is there any other way to make this cleanly?
There's no way to do this with mongoose, but there are ways of making it cleanly:
mongoPlaces
.find({
'person.types': {$in: ["student"]}
})
.select('family')
.lean()
.limit(3)
.exec(function (err, docs) {
var families = docs.map(function pluckFamily(doc) {
return doc.family;
});
return families;
});
In this example, map feeds each retrieved document to the function pluckFamily, and forms another array with all the values that that function returned.
If you're going to do a lot of this, you may want to check out the underscore library. It includes a pluck function.