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.
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 function to collect data when I click on the row, I keep the data in the object. When I log the object, it returns object type. But when I try to log its property, it is undefined.
branchToDivision: BranchDto;
onSelect(record: BranchDto) {
this.branchToDivision = record;
console.log(this.branchToDivision);
console.log(this.branchToDivision.brancH_CODE);
}
console screen
GetBranchForView {branch: BranchDto}
undefined
I don't know what problem is.
Here is Object definition
Console display
Does this work for you?
console.log(this.branchToDivision.branch.brancH_CODE);
I find the answer. Each line on the datatable is represented by a class called GetBranchForView. So when I try to catch the event I have to pass a param with type GetBranchForView. This works for me.
onSelect(record: GetBranchForView) {
this.item = record;
this.branchToDivision = record.branch;
}
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());
});
});
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 want to get some information out of a collection - in this example the user collection; but could be anything:
var result = Users.findOne({ _id: Meteor.userId() }).profile.anything;
In some cases the information is missing. For example if the DB is empty, I would get the error Exception in template helper: TypeError: Cannot read property 'profile' of undefined.
What would be the best way to prevent this if I'm using findOne and get an undefined result?
I would do something like:
var temp = Users.findOne({ _id: Meteor.userId() });
if (temp)
var result = temp.profile.anything;
But that looks not very elegant.
I cover this in some detail in my post on guards. This isn't really an issue with meteor or even the find operations - its just defensive programming in JavaScript. The generally accepted practice in cases where a guard may be needed is something like:
x && x.y && x.y.z
which covers the case where one or more of x and y are undefined.
You may run into situations where a long function is predicated on the existence of some piece of data. In those situations you may want to do something like:
user = Meteor.user();
if (!user) return;
...
// rest of function which assumes user is defined