Accessing single field from object in array - javascript

I'm using Meteor with MongoDB and can't seem to figure out how to access a single field from the objects in an object array.
My documents:
{
"_id" : "p6c4cSTb3cHWaJqpG",
"createdAt" : ISODate("2016-05-11T11:30:11.820Z"),
"username" : "admin",
"contacts" : [
{
"when" : ISODate("2016-05-11T11:30:32.350Z"),
"who" : "4YBufbE9PByJBkasy"
},
{
"when" : ISODate("2016-05-25T11:52:49.745Z"),
"who" : "z792kEEYbxyzyEAKp"
},
{
"when" : ISODate("2016-05-26T13:47:43.439Z"),
"who" : "4YBufbE9PByJBkasy"
},
{
"when" : ISODate("2016-05-26T13:48:22.828Z"),
"who" : "4YBufbE9PByJBkasy"
}
]
}
I want to check if a userId is in any of the objects, specifically in the who fields.
My Server-side code:
var me = Meteor.userId();
var findMe = Meteor.users.findOne(me);
if (_.include(findMe.contacts, {who: 4YBufbE9PByJBkasy})){
console.log("found in array");
}else{
console.log("Not found in array");
}
}
I have tried this several different ways, but came up with nothing.
When I console.log(findMe.contacts);, it returns the whole array like it should. but when I try to console.log(findMe.contacts.who);, it returns undefined.
Just need some direction on how to access the field of the object array. Thanks!

Looping through an array to see whether it contains a value is easily
done with Array.prototype.some:
var data = {
"_id" : "p6c4cSTb3cHWaJqpG",
"createdAt" : "2016-05-11T11:30:11.820Z",
"username" : "admin",
"contacts" : [
{
"when" : "2016-05-11T11:30:32.350Z",
"who" : "4YBufbE9PByJBkasy"
},
{
"when" : "2016-05-25T11:52:49.745Z",
"who" : "z792kEEYbxyzyEAKp"
},
{
"when" : "2016-05-26T13:47:43.439Z",
"who" : "4YBufbE9PByJBkasy"
},
{
"when" : "2016-05-26T13:48:22.828Z",
"who" : "4YBufbE9PByJBkasy"
}
]
};
var hascontact = function(contacts, id){
return contacts.some(function(contact){
return contact.who === id;
});
};
console.log(hascontact(data.contacts,'4YBufbE9PByJBkasy'));
console.log(hascontact(data.contacts,'z792kEEYbxyzyEAKp'));
console.log(hascontact(data.contacts,'asdfasdfasdfasdfa'));

Related

Mongoose - go through object

Using mongoose on node.js I'm trying to find all games where player game.players.id equals the id I passed.
Schema:
var Game = mongoose.Schema({
id: String,
date: { type: Date, default: Date.now },
game: Object,
isOnline: Boolean
});
I'm not sure what is wrong in this function but it returns empty array:
var specificGameStatistics = function (user, game) {
var deferred = q.defer()
Game.find({ "game.players.id" : user, "game.rules.gameType": game.gameType, "game.rules.quatro": game.quatro}, function(err, data) {
deferred.resolve(data);
});
return deferred.promise;
}
////////////////////USAGE///////////////
var testGame = {rules: {gameType : 1, quatro : null}}
UsersCtrl.specificGameStatistics(data.id, testGame).then(function(userData) {
console.log(userData);
});
And here is the example of the game already saved in database:
{
"isOnline" : true,
"game" : {
"numberOfPlayers" : NumberInt("1"),
"players" : [
{
"id" : "58a2c0ecd8ba9f8602836870",
"name" : "PlayerName",
"type" : NumberInt("1"),
"avgStatistic" : "30.00",
"numbersHit" : NumberInt("1"),
"totalScore" : NumberInt("60"),
..............................
}
], //there is more players here
"rules" : {
"gameType" : NumberInt("1"),
"quatro" : null,
"rounds" : NumberInt("1"),
} // there is more in JSON object
...............................
"_id" : ObjectId("58aed4aeea20ecdf0c426838"),
"date" : ISODate("2017-02-23T13:25:18.284+01:00"),
"__v" : NumberInt("0")
}
I have tested the player ID to be equal and it is but still it returns empty array. Test code:
///////////TEST//////////////
console.log(data.id, "58a2c0ecd8ba9f8602836870");
if (data.id === "58a2c0ecd8ba9f8602836870") {console.log("this is true");}
var testGame = {rules: {gameType : 1, quatro : null}}
UsersCtrl.specificGameStatistics(data.id, testGame).then(function(userData) {
console.log(userData);
});
//////////TEST///////////////
and it returns:
58a2c0ecd8ba9f8602836870 58a2c0ecd8ba9f8602836870
this is true
[]
--------------------------------------------------------------------------------------------------------
Answer: With help of Deividas Karžinauskas the solution is:
Game.where('game.players.id', user).where('game.rules.gameType', game.rules.gameType).find({}, function(err, data) { //, "game.rules.quatro": game.quatro
deferred.resolve(data);
});
This is because of the additional rules that you specify ({gameType : 1, quatro : null}), which do not exist in the player object (
{
"id" : "58a2c0ecd8ba9f8602836870",
"name" : "PlayerName",
"type" : NumberInt("1"),
"avgStatistic" : "30.00",
"numbersHit" : NumberInt("1"),
"totalScore" : NumberInt("60"),
..............................
}
). You can confirm this by simply looking for a game by id.
If you want to add these rules then you should find all games which match these rules and then look for the games of a specific player.

MongoDB .find() only ObjectId's embedded in an Array.

I am trying to get only the ObjectId's from One specific Document that is embedded in the projects Array.
Basically I am trying to make a database that will have users and each user will have there own projects.
Thank you !
db.users.find().pretty()
{
"_id" : ObjectId("5762c0cf2b9a78006373a684"),
"name" : "seq",
"pass" : "seq",
"projects" : [
{
"pid" : ObjectId("5762c0ba2b9a78006373a682"),
"name" : "aaa"
},
{
"pid" : ObjectId("5762c0ba2b9a78006373a683"),
"name" : "bbb"
}
]
}
{
"_id" : ObjectId("5762c28d2b9a78006373a687"),
"name" : "leq",
"pass" : "leq",
"projects" : [
{
"pid" : ObjectId("5762c2892b9a78006373a685"),
"name" : "ccc"
},
{
"pid" : ObjectId("5762c2892b9a78006373a686"),
"name" : "ddd"
}
]
}
let say we want two pids
{"pid" : ObjectId("5762c0ba2b9a78006373a682")} and
{"pid" : ObjectId("5762c2892b9a78006373a686"),}
and only inner documents
so required response should look like:
{
"_id" : ObjectId("5762c0ba2b9a78006373a682"),
"name" : "aaa"
},{
"_id" : ObjectId("5762c2892b9a78006373a686"),
"name" : "ddd"
}
Aggregation framework can manipulate documents, match only needed ones and transform inner structure by project phase:
var match = {
$match : {
"projects.pid" : {
$in : [ObjectId("5762c0ba2b9a78006373a682"),
ObjectId("5762c2892b9a78006373a686")]
}
}
}
var unwind = {
$unwind : "$projects"
};
// now move array objet as top level object
var project = {
$project : {
_id : "$projects.pid",
name : "$projects.name",
// list other fields here
}
}
db.vic.aggregate([match, unwind, match, project])

How to remove object from numeric array with mongoose

I got this kind of document
{
"_id" : "5339be1d9a703ab8708b45675339bed39aac7",
"description" : "data",
"name" : "data",
"members" : [
{
"user" : {
"$ref" : "users",
"$id" : ObjectId("5339be1d9a703ab8708b4567"),
"$db" : "someDb"
},
"type" : "Principal"
},
{
"user" : {
"$ref" : "users",
"$id" : ObjectId("5339c0c59a703a5d1f8b4569"),
"$db" : "someDb"
},
"type" : "Regular"
}
],
"owner" : "5339be1d9a703ab8708b4567",
}
And I'm trying to pull an element from the array members, finding it by the $id in user object.
I'm using Mongoose ODM.
This is my function:
> var conditions = {"_id" : data.guildId},
> update =
> {
> $pull :
> {
> 'members.user.$id' : new mongoose.Types.ObjectId(data.userId)
> }
> };
> var options = {upsert:false};
>
> Guild.update(conditions, update, options, leaveRoom);
There are no errors reported in my node js server or in the mongo log file, but the document remains unaffected.
The pull syntax you have is wrong. $pull takes an array, which in your case is "members".
You want this update instead:
{ "$pull" : { "members" : { "user.$id" : <your-condition> } }

Unable to print BSON object from javascript

My mongoDB collection looks like this :
{
"_id" : ObjectId("5070310e0f3350482b00011d"),
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
}
and this is the .js code i use to print the contents :
c = db.contacts.findOne( { "emails.email" : { $ne : null } }, { "emails" : 1 } )
print(c._id.toString() + " " + c.emails[0]);
when I try to run this javascript file, it is just displaying the id but not the email array.
output:
5070310e0f3350482b00011d [object bson_object]
but when I try c.emails[0].email is is giving proper result. i.e. peter.loescher#siemens.com
All I need is I want to display the whole emails embedded object.
i.e.
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
Where I am going wrong?. Any help would be appreciated.
You need printjson to output a nicely formatted JSON:
printjson(c.emails[0]);
Here it is the documentation.

How to delete deep array in mongodb?

I am trying to delete "virtualNumber" : "12345" in the following document:
{
"_id" : ObjectId("50a9db5bdc7a04df06000005"),
"billingInfo" : null,
"date" : "dsfdsfsdfsd",
"description" : "sdfsdff",
"pbx" : {
"_id" : ObjectId("50a9db5bdc7a04df06000006"),
"did" : {
"1234567890" : {
"inventoryId" : "509df7547e84b25e18000001",
"didcountry" : "india",
"didState" : "bangalore",
"routeType" : "CallForward",
"didNumber" : "1234567890",
"didVirtualNumbers" : [
{
"virtualNumber" : "12345"
},
{
"virtualNumber" : "56789"
}
],
"id" : ObjectId("50a9db9acdfb4f9217000002")
}
},
},
I am using node.js, so I constructed a query in JavaScript:
var query = {_id: ObjectId("50a9db5bdc7a04df06000005")};
var obj = {};
obj["pbx.did.1234567890.didVirtualNumbers.virtualNumber"]=12345;
//problem
collection.update(query,{$pull:obj});
You need to match the array element like:
{"$pull": {"pbx.did.7259591220.didVirtualNumbers": {"virtualNumber": "12345"}}}
So you should change your code to:
obj["pbx.did.7259591220.didVirtualNumbers"]={"virtualNumber": "12345"};
Please refer to http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull
It mentions the pull field should be an array.

Categories