I am get the multiple fields from my document in firestore and then I use the data to set the same fields from the doc into another doc. There are a lot of fields in one document. How can I do this without writing each field name?
db.collection('sourceCollection').doc('sourceDoc').get().then( snap => {
const data = snap.data()
//from what I see this is an array now with fields in it
db.collection('newCollection').doc('newDoc').set({
//What do I put here so I can set the content of data as separate field in the newDoc
//if I do the following I get an array field called `data` within the new doc which is not what I want; I need the content of the `data` to be SEPARATE fields in the newDoc
data
//I also dont want to write each field because there are too many so the following wouldn't work for me:
fieldName: data.sourceDocFieldValue,
...
})
});
Just pass data without putting it in curly braces.
db.collection('newCollection').doc('newDoc').set(data);
Related
I have 3 subcollections nested under one another under one single main collection.
I want to get all the documents under 'colection3' for each document in 'collection2' for each document in 'collection1'
I want to query something like -
admin.firestore().collection('collection1').doc('FOR ALL DOCS IN COLLECTION 1').collection('collection2').doc('FOR ALL DOCS IN COLLECTION 2').collection('collection3').get()
My question is, can I make such query ? Will following query work ?
collection('collection1/*/collection2/*/collection3')
Is this a valid path? What does "*" indicates?
I tried something like this,
const baseRef = admin.firestore().collection(`collection1/*/collection2/*/collection3`);
const querySnap = baseRef.get()
It returned me a querySnapshot but when I tried to loop through this querySnapShot, it didn't print anything
querySnap.forEach(doc => console.log(doc.id))
output was nothing.
I was expecting that doc Ids should get printed in the console.
This can be achieved with collection group level queries.
The collectionGroup option returns all documents within the collection group you have created.
const allDocsQuery = admin.firestore()
.collectionGroup('collection1');
await allDocsQuery.get().then((snap) => {
// do operations with your data
});
Note that you will need to create a collection group in order to use this - it will throw an error with a link to the creation page, but you can also do it by following the documentation in the link above.
const generatedEvent = await Event.create(req.body);
res.send(generatedEvent);
I am getting some data from the request body and I can generate a new Event. And I'm returning the event to client when it has generated. But I don't want to return all fields with event. I want to make filter operation like how we are using select function like this: Event.find().select({title:1,description:1})
How can i use this select func with Model.create?
If you take a look at the mongoose-source code, you can see that Model.create returns a promise with the created/inserted documents. There's no way to specify a filtering-options to return only specific fields.
Of course you could do a .find() in combination with a .select() call after creating/inserting a new record but that would result in one extra DB-query for each insert which does not make a lot of sense.
You could instead just return the desired properties from the returned document, since you know that a new document was inserted successfully with the provided data, when the promise resolved. So you could simply do:
res.send({title: generatedEvent.title, description: generatedEvent.description});
Model.create() internally doesn't fetch the document from the database, rather it actually returns the result whether it's inserted successfully or not. If successful, mongoose will return the original mongoose document that mongoose created before sending to the database.
So you could just select the fields by yourself. Using es2015 Object destructuring assignment and Object shorthand property names would help writing more concise code.
const { title, description } = await Event.create(req.body); // Object destructuring
res.send({ title, description }); // Object shorthand property names
As far as I know, with PUT one can create a resource if it doesn't exist or it is going to replace the old one with a new one.
I want to create a resource and being able to update it, not create more resources, using Node.js/Express and MongoDB.
So, I wrote this code:
app.put('/entries/:entry_id/type', (req, res) => {
const entry = new Entry (req.body);
entry.save();
res.end();
})
in Postman there is a PUT request, having the url: localhost:5000/entries/2/type
After sending it once, it creates an entry in the dabatase. All good!
But let's try to send the same request again. Now there are 2 entries in the database. I would expect to be one, because the same request was sent.
In the database they have the same data, same schema but they do have an extra field,
"_id":{"$oid":"5e8909e60c606c002axxxxxx"},, which is has the last character different.
Why are there created more entries of the same data while I was expecting to have only one entry in the database?
Mongo automatically creates a default index named _id on every collection when it is created. If you insert a Document into a collection without specifying an _id it will generate a new ObjectId as the _id field.
To get around this you can use findOneAndUpdate with upsert:
Entry.findOneAndUpdate({ entry_id: req.params.entry_id }, { <content> }, { upsert: true })
However this will update the document if it exists already instead of creating a new one. If you further wish to not change the Document at all if it already exists, then you can surround your <content> with $setOnInsert.
what i exactly want is to store some Data Locally in a Array of Objects in my Program so that i can use that Data all day long and by the End of the Day i want to delete it without the use of Databases. I have a Json data and i want to Store them as object with a universally unique identifier (uuid) in an Array or data Structure so that i can use it in my Program, i cant use a Database, i think i must find a way to store the Objects in a global Array but i want to append new Objects to that Array without deleting the Objects that are already stored in that Array. I'm using Node js, I'm pretty sure there is a way to do this but i dont know how. I ll apreciate some Help
I tried to Declare classes with Array Property and Store my Data in that Array but when i reexecute the code, the data is deleted and i lost my Data, but i must find a way like a Local Storage in a global Array where my Data will be safe if I append some Objects to that Array and I'm Ok if that Data will be deleted at the End of the Day if I turn off my Laptop for example or if I end the Program and close Vs Code. I tried also to declare it in extra files and call it from the main program but nothing worked
// this is a library to create a universilly unique id
const uuid = require("uuid/v1");
var todo_list = {
todos: [],
register : function(todo) {
this.todos.push({
id : uuid(),
todo: todo
})},
size : function() {return this.todos.length },
display : function() {
this.todos.forEach(t=> {
console.log(t);
});
}
}
function createtodo(id, name, region) {
return {
id : id,
name : name,
region : region
};
}
todo_list.register(createtodo(2,"test6", "leipzig"));
console.log(todo_list.size());
console.log(todo_list.display());
i expect that when a register a new todo that it ll be appended in the todos Array Property and not replace what actually inside the todos in the moment.
If i call the function register 5 times then 5 objects will be stored in my todos Array but if I Comment the code of register function calling and execute the Program another time, then my data will be lost and the result of the size function will be 0 or undifined. the result that i want is that my data will be stored in an extra global Array where the data will not be lost even after i change the code but i understand that the data will be lost if i close the program somehow
I get this strange behavior. Here's the thing: I make a database query and want to delete an element of the json returned by the query. So this doesn't seem to work (i.e. the element is not deleted),
var user=json;
delete user.element;
while this works
var user={element:json.element,blement:'stuff'}
delete user.element;
I think what you are referring to as JSON is actually a Mongoose document object given the tags you added to your question. Since that object is attached to it's "schema", you may have rules in there such as a "required" field or such that are interfering with the operation you are trying to do.
In order to get a raw form of the Object back, simply use the .toObject() method on the document result:
Model.findOne({ _id: id}, function(err,doc) {
var raw = doc.toObject();
delete raw.element;
console.log( raw );
});
Of course you can always just omit the field from being returned in the query result with the basic form provided by .select():
Model.findOne({ _id: id}, '-element', function(err,doc) {
console.log( doc );
});
Either form would remove that particular field from the response, but if you possibly want more control over the result than what can be provided by the field projection from .select() then use the .toObject() form and manipulate just as a plain JavaScript object.