Mongo find Document after Insert - javascript

i use sails js 0.12.14 with mongodb. if i try to get a document after insert the document the document is empty
Products.create(product).exec(function(err, createdProduct) {
Products.find({_id : createdProduct.id}).exec(function(err, foundProductAfterCreate) {
console.log(foundProductAfterCreate);
})});
Can anybody explain why the document is not available?
Update:
This is the correct code for me...
Products.create(product).exec(function(err, createdProduct) {
Products.find({_id : createdProduct[0].id}).exec(function(err, foundProductAfterCreate) {
console.log(foundProductAfterCreate);
})});

The doc you are querying for is literally the same one you already have
Products.create(product).exec(function(err, createdProduct) {
// handle the error...
console.log(createdProduct); // the full record
});
createdProduct is exactly the same object you would get if you queried by id.
If you do ever need to query by id, sails does a fairly comprehensive switch from _id which is the mongo standard, to id with no underscore. You would do that like this:
Products.findOne({id: createdProduct[0].id}).exec(function(err, foundAgain) { // etc
...no underscores anywhere unless you use .native for more basic mongo query access.

Related

Query stored values that contain specific string

I have a small realtime firebase database that's set up like this:
database
-messages
--XXXXXXXXXXXX
---id : "XXX-XXX"
---content : "Hello world!"
It's a very simple message system, the id field is basically a combination of users id from my mysql database. I'm trying to return all messages that match one of the ids, either sender or receiver. But I can't do it, seems like firebase only support exacts querys. Could you give me some guidanse?
Here's the code I'm working with
firebase.database().ref("messages").orderByChild("id").equalTo(userId).on("value", function(snapshot)
I'm looking for something like ".contains(userId)"
Firebase supports exact matches (with equalTo) and so-called prefix queries where the value starts with a certain value (by combining startAt and endAt). It does not support querying for values that end with a certain value.
I recommend keeping a mapping from each user IDs to their messages nodes, somewhere separately in their database.
So say that you have:
messages: {
"XXXXXXXXXXXX": {
id : "YYY-ZZZ",
content : "Hello world!"
}
}
You also have the following mappings:
userMessages: {
"YYY": {
"XXXXXXXXXXXX": true
},
"ZZZ": {
"XXXXXXXXXXXX": true
}
}
Now with this information you can look up the messages for each user based on their ID.
For more on the modeling of this type of data, I recommend:
Best way to manage Chat channels in Firebase
Many to Many relationship in Firebase
this artcle on NoSQL data modeling

Redirect to new Mongo Saved ID after Express POST?

In my POST request, I'm saving a new document into my mongo database. After the database is saved, can I do a res.redirect to that exact document ID?? I'm unsure of how to do this. I can't find any tutorials, documentation, or stackoverflow questions that seem to answer exactly what I'm looking for.
Can I do something like this? Where the :id is the Id of the document I just saved in mongoose/mongo?
newItem.save().then(res.redirect('/results/:id');
I expect the user to submit a post request. I'm saving the information into a mongo document through mongoose. Then after saving it I'd like to redirect to a new URL with the ID of the saved item on that page.
Of course you can.
The save() method can accept a callback so you can get the _id field of the saved document.
One way of do it would be:
newItem.save((err, itemSaved) => {
if(err) {
next(err);
}
const itemId = itemSaved._id;
res.redirect('/results/' + itemId);
});
Hopefully, this will solve your problem.
P.S.
There's no need to use a colon on redirect's path. Beware with that, 'cause using it will give you a Cast Error.

How can I retrieve data from firebase database by its value in Web App?

I am making a complaint portal and I want to assign id to the people who register.
My data structure in firebase like below:
fir-web-learn-51ffc
complaint
-Kwe6QXol8DV-uMDxIe7:"Hiii"
-KweCaYQrgG75BiJW3dA:"Hooooo"
and I have used this code for insertion:
function submitClick()
{
var complaint=document.getElementById('complaint').value;
var database=firebase.database().ref().child("complaint");
database.push().set(complaint);
}
for the above code, How can I retrieve the Name(Kwe6QXol8DV-uMDxIe7) by its value(Hiii). I have tried the code given on Google Firebase Documentation and Youtube but didn't work.
You'll use a Firebase query for that with orderByValue. So something like this:
var ref=firebase.database().ref().child("complaint");
ref.orderByValue().equalTo("Hiii").once("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key);
});
});
Aside from the query itself, the main thing to note is the snapshot.forEach() in the callback. This loop is needed since a query can potentially match multiple results.

Finding MongoDB Document by ID

I'm using Node.js and MongoDB with my database hosted on MongoHQ (Now compose.io). I have a general understanding document IDs are converted to hex strings but I can't figure out how to retrieve a document using its ID.
My document has the ID _id: ObjectId("53f13064b5a39cc69f00011b") as in that's how it's displayed in Compose's interface. When I retrieve the document by brute force, the ID is shown as _id: 53f13064b5a39cc69f00011b.
What do I use in Node.js to retrieve this document? The query:
systemData.find({_id: "53f13064b5a39cc69f00011b"}).toArray(function(err, data) {//do stuff}
returns an empty set but so does querying with an object ID object
systemData.find({_id: new ObjectID("53f13064b5a39cc69f00011b")}).toArray(function(err, data) {//do stuff}
What am I missing?
You should be able to use:
systemData.find({_id: ObjectID("53f13064b5a39cc69f00011b")})
No need for the "new" on the beginning.

how to update a Mongo.db collection in meteor.js?

I have a collection that I need to update when the user presses a button.
I just need to change one variable to another.
In the console, this line of code works:
db.users.update({username : "Jack"},{age : 13, username : "Jack"});
But when I put in this code:
Template.body.events({
'click #updateAge' = function() {
{
alert();
db.users.update({username : "Jack"},{age : 13, username : "Jack"});
}
}
})
into my JavaScript file for Meteor.js, it doesn't do anything at all (I don't get an error message, and I see the alert, but the update just doesn't work).
I've read through the Meteor Documentation on updating, but I just can't seem to get it to work.
Does anybody know what I'm doing wrong here?
Found the problem.
Since I defined my database in my lib.js file
users = new Meteor.collection("users");
I don't need to put a db in front of the db.users.update({_id : "Jack"},{...}). I also need to find the document using the given mongo _id, not the identifier "username".
so the appropriate code would be
users.update({_id : "Jack"},{$set:{age : 13, username : "Jack"}});
In mongodb, you will have to use an update operator(for ex: $set). Otherwise, your document will overwritten by the update object you are passing(I am not sure that's what you want). I think, its works same in meteor. So, you will have to do something like this:
Meteor.users.update({username : "Jack"},{$set: {age : 13}});
This might not be the problem as you've stated you do not get a error message but to be sure: have you already allowed the user to update documents in the user collection?
Something like:
(in collections/permissions.js)
user.allow({
update: function (userId) {
// the user must be logged in to allow updates
return (userId != null);
}
})

Categories