In a database reference, how can you iterate over its last n children? Something like this:
firebase.database().ref('/path').on('value', function(data) {
data.limitToLast(n).forEach(function(child) {
console.log(child.val());
});
});
I tried something similar to the above snippet, but I got an error:
TypeError: data.child(...).limitToLast is not a function [Learn More]
So I think there is no limitToLast() method for a datasnapshot. Then I tried forEach() on a database reference with limitToLast(), but I got an error; I think database references don't have a forEach() method.
How do I do what I'm trying to do?
limitToLast() is a method on Query (and Reference), not on DataSnapshot. You use it when specifying your query, so that the server only returns the number of elements you're looking for in the snapshot that's delivered to your callback.
firebase.database().ref('/path').limitToLast(n).on('value', function(data) {
data.forEach(function(child) {
console.log(child.val());
});
});
Related
According to the documentation here, it should be possible get an id for a not-yet-created firestore document, add it the object to be saved, and then persist it like this:
// Add a new document with a generated id.
var newCityRef = db.collection("cities").doc();
// later...
newCityRef.set(data);
In my application, I follow this pattern with the following code:
async createNewProject(projectObject : Project) : Promise<boolean> {
let doc = this.firestore.collection("projects").doc();
projectObject.id = doc.ref.id;
try {
await doc.set(projectObject);
} catch(err) {
console.error(err);
return false;
}
return true;
}
When it runs though, i get an error in the console:
FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: undefined
Can anybody shed any light? I've seen other folks on her referencing this method (using the doc method with no parameters as the solution to the problem, yet others are seeing this error. Is this some kind of API on the Angular implementation of the API, or a problem at the firebase side of things (or did I do something wrong?)
The doc() method returns a DocumentReference, which does not have a ref property but has an id one. Therefore you need to do:
projectObject.id = doc.id;
instead of
projectObject.id = doc.ref.id;
I have a Node.js script that used to work, but after I switched to another VM it does not work anymore. Can anyone see what the problem is? Here is the function, db is a database:
this.start = function() {
logger.debug('Starting up.');
db.serialize(() => {
db.run("DELETE FROM jobs WHERE status = 'failed'")
.run("UPDATE jobs SET status = 'queued'", (err) => {
if (err) {
logger.error(err.message);
} else {
logger.info('done');
}
});
});
}
Now I get the following error:
TypeError: Cannot read property 'run' of undefined
at Database.db.serialize ()
at TransactionDatabase.serialize
at module.exports.start
at Object.<anonymous>
...
The error is pointing at the second ".run".
My Node.js version is 10.4.1, sqlite3 version 3.8.2.
What am I missing? Some module?
I think I found the answer. Chaining run() runs the queries nearly at the same time. According to this answer, the function run() starts the query, but returns immediately.
However, if you serialize and chain, those two methods cannot be used at the same time. You are trying run queries sequentialy, but also at the same time.
Although, depending on your needs, you can nest serialize, parallelize or callbacks, as shown in the "control flow" doc.
I guess the method serialize() "locks" chaining by changing the return value of run() to undefined.
I am trying to access the properties of a returned MongoDB (mongoose) find.
If I try to console log the whole object, I can see it all. But if I try to log a property, I get undefined. The object is there!
function getAll () {
let d = q.defer();
User.find({}, function (err, docs) {
if (err) {
d.reject(err);
}
for(let user of docs) {
console.log(user); // This works!
console.log(user.email); // This returns undefined!
}
d.resolve();
});
return d.promise;
}
Any idea?
I also tried to use JSON.parse in case it was stringified (just to make sure) but it wasn't.
UPDATE
So seems like I can access the result using user._doc.email.
But what causes this? I don't remember having to do this before.
If a field in your document shows up when you console.log the whole document, but not when you directly access that field, it means the field is missing in the model's schema definition.
So add email to the schema of User.
I get the following error while doing aggregate in node.js.
Error: TypeError: Cannot call method 'toArray' of undefined
doctorsCollection.aggregate([
{$project:{"treatments._id":1, "treatments.price":1}},
{$unwind:"$treatments"},
{$match:{"treatments._id": parseInt(treatments[i])}},
{$sort:{"treatments.price":-1}},
{$limit:1}
]).toArray(function(err, result) {
console.log(err);
});
I have no idea what's going on. Any help would be appreciated. Thanks!
From the .aggregate documentation for the node.js MongoDB driver, the method does not return a cursor unless you specify for it to return a cursor as an option. By default it will return null so the .toArray method doesn't work / make sense.
There are several ways to handle it and the documentation provides a ton of examples. In your case you can add {cursor: {batchSize: 1}} as the second argument to .aggregate and it will work.
Firebug is complaining about this line:
$("#original-description").text(response['course']['original_description']).hide();
Do I have a syntax error? Looks fine to me.
More context:
bindOnSuccess($('#course-search'), function(response) {
if (!response) {
$("#system-status").text("Sorry, no course could be found for that search.");
}
else {
$(".dept-code").text(response['course']['dept_code']);
$(".course-number").text(response['course']['number']);
$(".course-title").text(response['course']['title']);
$("#div-original-description").show();
$("#original-description-teaser").show();
// error here
$("#original-description").text(response['course']['original_description']).hide();
$("#td-required-for").text(response['analysis']['cRequiredFor']);
}
});
response is a JSON object. Could this problem be caused by invalid subscripts?
Firebug's error is:
$("#original-description").text(response.course.original_description).hide is not a function
The other answers are pointing out incorrectly - .text() returns the jQuery object. You are probably referencing an undefined property. I can replicate this:
$('<p>').text(undefined).hide()
Make sure you are referencing the right property in the JSON.
TypeError: $("<p>").text(undefined).hide is not a function { message="$("<p>").text(undefined).hide is not a function", more...}
If you want to query the object live you can simply do
window.o = response in your callback function and just play around with it in Firebug console.