converting Mongoose returned array to regular JSON - javascript

In a Node.js App, i want to fetch some data from database via Mongoose. i do it like this:
Users.find({_id:userID}).exec(function(err, users){
});
because users is an Array like Mongoose object, i cant do this:
users.toJSON();
this works if i use findOne but right now doesn't work. also users.toObject() doesn't work and i get this error:
object has no method 'toObject'
if i use lean() in query like this:
Users.find({_id:userID}).lean().exec(function(err, users){
});
this works but it has other problems. for example, if an array value has no value, instead of showing it like this:
myval:[]
doesn't show that key/value pair at all!!
What i want is that i have to edit that users result and apparently, its Mongoose object and i cant. because of that i have to convert it to a regular JSON but how?

Just use findOne instead of find and you'll be able to edit your instance.
If you absolutely have to use find then know that users parameter is the array of user instances, so just loop through them and edit them one by one.
Users.find({_id:userID}).exec(function(err, users){
users.forEach(function(user){
// edit my user here
});
});

Related

JSON Array from String

I have an array of JSON plots which I store in MySQL. When I retrieve this information from MySQL it is given as one long string. How can I restore this back into an array of JSON objects using Javascript? I'm running this using NodeJS and MySQL package.
My data is returned like the following:
'[{"x":0,"y":0},{"x":1,y:1},{"x":2,"y":2}]'
What I would like to be able to do is use the data like:
var data = [{"x":0,"y":0},{"x":1,"y":1},{"x":2,"y":2}];
console.log(data[0].x);
I've had a try using JSON.parse and originally stored the data using JSON.stringify on the array, but it is not behaving as I would expect.
Are there any methods or packages available to handle this?
Edit: I realize now that this is not JSON but rather objects. Apologies for the wrong terminology here, but my problem still remains.
var data = new Function ('return ' + dataString)();

MongoDB - How to build query string with [Object] as a field

I'm building up a string in Meteor to drill down into my data from MongoDB.
My data looks like this:
Data
In my Meteor projects JavaScript I have built up the string like so:
const concentrationTier1 = MyCollection.findOne({_id: "85gh43tnb23v4"}).BILL.Sovereign.USD.Short.Low.High.N.ARGENTINA.IssueName00006.ARARGE5203E7;
console.log(concentrationTier1);
But now in my console it is returning the following:
Console
How would I add [Object] to my string to be able to display the next part of the data?
I have tried .[Object] .Object .0 and of course these didn't work.
Can any body help with this one?
Many thanks,
G
You would have to access that array element as in plain normal javascript, like this:
...IssueName00006.ARARGE5203E7[0].concentrationTier1
And the reason is your MongoDB query already returned a document, you're not querying in your database anymore so there's no need to use dot notation to access array elements.

Meteor.js 1.0: How do I return an _id outside of ObjectId using this._id?

I'm going through the simple tutorial on the site Meteortips.com to learn about session variables, but I'm having trouble retrieving the object id.
When I follow the instructions word for word, I end up with this code:
Template.leaderboard.events({
"click .player": function(){
var playerId = this._id;
Session.set("selectedPlayer", playerId);
console.log(playerId)
}
})
When I log playerId, according to the tutorial, I am supposed to get the id in the form: 546d2e4e1c9a86a33e37005d, but instead, I get it in the form:
LocalCollection._ObjectID
{_str: "546d2e531c9a86a33e37005e",
toString: function,
equals: function,
clone: function,
typeName: function…}
I then thought to try using toString(), which ended up making the equivalency test work in a later part of the tutorial (so it solved the problem), but it still returned ObjectID("546d2e461c9a86a33e37005c") when I was expecting the id without the ObjectID() thing wrapped around it.
How can I get the id without all the extra stuff?
Edit
It might be worth noting that I did all of this on a Chromebook using Nitrous.io. I coped the code from Nitrous.io into Meteorpad here and it works like it's supposed to.
The only way I was able to get the id I wanted while in Nitrous.io was by using this._id._str instead of just this._id. I still have no idea why that is... But that's what happened.
If you didn't give a value for _id when inserting an item to your Mongo db directly, it will use a special ObjectID for _id. If you insert an item using Meteor Collection it will use a random 17 character string by default for _id. Just add data using Meteor collections or manually set the _id to a random 17 character string when you add data.

Searching a MongoDB collection based on another

I have a document called Mapping, which has an _id and an array of objects called Mappings.
I have another collection called NewMappings. For each _id in NewMappings, I need to search within the array of Mappings (of Mapping collection) and return the _id of Mapping.
I wrote something like this, but it failed to return anything.
var d=db.NewMappings.find();
d.forEach(function(item){
db.matching.find({Mappings: {$elemMatch : {TargetId: item._id}}})
})
however, this query returned values
var d=db.NewMappings.find();
db.matching.find({Mappings: {$elemMatch : {TargetId: d[0]._id}}})
Am I missing something?
Please help me. I am in dark. thanks in advance.
One way, if you just want to see the results is:
var d=db.NewMappings.find();
d.forEach(function(item){
db.matching.find({Mappings: {$elemMatch : {TargetId: item._id}}}).forEach(printjson)
})
You can also use the aggregation framework
Sounds like you're trying to do a Join, which isn't explicitly supported in MongoDB. You'll need to either use a few aggregation functions to flatten the data or a mapreduce.
Here's an example using mapreduce to restructure information:
http://cookbook.mongodb.org/patterns/pivot/

Node.js MongoDB .findOne returns best match when querying a String

If I create a document in MongoDB using the create method.
Ua.create({myStringField: 'myStringData'}, function(err, myUa){
callback(err,myUa);
});
Later I then want to search for a new string in the database and use this method.
Ua.findOne({myStringField: 'myStringDataNEW'}, function(err, myUa){
callback(err,myUa);
});
Notice that I set the original myStringField with data 'myStringData' and am now searching for 'myStringDataNEW'. The findOne() method returns the document containing 'myStringData' as the result of this query.
How do I query only for exact matches to strings in MongoDB?
Many thanks for your help.
I'm pretty certain you are getting confused. Your findOne call will do an exact, case-sensitive match. To do partial matches or case-insensitive you need to use a RegExp instance not a basic string. My suggestion is to make a simple test case separate from your app, and my suspicion is the DB is not behaving the way you think it is.

Categories