How to add new items to an array in MongoDB - arrays

I'm trying to add a new item to whichever name that was passed in under whichever id. My first problem is that it seems like its not grabbing the values from any of my variables (name, item, id), instead just using them as object keys. My next issue is that when I tested by hard-coding sample table info onto here, it wasn't adding more items to that array, but simply replacing the entire array with whatever values I had here.
function addlist(name, item, id){ // Add to user's list
console.log(id);
db.collection('newcon').update({_id: id}, { "$set": { "$push": { name:item } } });
ret(id);
}

$set is not an array update operation.
The $set operator replaces the value of a field with the specified value.
You just want to use $push by itself, as in
.update({_id: id}, {$push: {name: item}})
You can't interpolate object property names in raw object declarations, so if you want to use a variable name you will have to create an object to do this:
var obj = {};
obj[name] = item;
You can then pass this to .update, {$push: obj}

Related

How to remove a key in object in array

I have an address that looks like this
let address = [{"_id":"6013a6ef20f06428741cf53c","address01":"123","address02":"512","postcode":"23","state":"512","country":"32","key":1},{"_id":"6013a6eh6012428741cf53c","address01":"512","address02":"6","postcode":"6612","state":"33","country":"512","key":2}]
How can I remove '_id' and 'key' together with its Key and Value Pair.
And can you please let me know how does this type of array is called? Is it called Object in Array? I keep seeing this type of array but I have no clue how to deal with this, is there like a cheatsheet to deal with?
You can access the property of the object like this:
address[0]["_id"]
// or
address[0]._id
and you can delete the property like this:
delete address[0]["_id"]
// or
delete address[0]._id
Where 0 is the 1st index of the array. You might need to iterate over your array and remove the property from each object:
address.forEach(a => {
delete a._id;
delete a.key;
});
First, this type of array is called "Array of Objects" (objects inside array)
Second, you can generate new set of array by delete the key which you want to remove by,
let newSetOfArray = address.map((obj)=> {
delete obj._id;
delete obj.key;
return obj;
});
console.log(newSetOfArray); // this array of objects has keys with absence of _id & key.

How to order a dictionary by value in AngularJS

I've a REST api that returns the list of locales as dictionary:
{
"en-uk": "English UK",
"en-us": "English USA",
...
}
This dictionary is correctly ordered alphabetically by value.
When AngularJS receives it via HTTP, the dictionary gets automatically re-sorted by key, so when I bind to a select element the list of options is ordered by key, and the alphabetical order by key doesn't match the one by value, I get a wrong sorting.
The problem I suppose is due to the fact that such dictionary becomes basically one object with 800+ properties. How do I sort it by value?
First: You have to find all keys.
Second: Iterate all the keys.
Third: Then sort the array with values.
Please use the following:
let obj = {
"en-us": "English USA",
"en-uk": "English UK"
};
// Get an array of the keys:
let keys = Object.keys(obj);
// Then sort by using the keys to lookup the values in the original object:
keys.sort(function(a, b) { return obj[a] > obj[b] });
console.log(keys);
console.log(obj[keys[0]]);
You can modify the way you send the response from the server. Instead of sending the response as an object, send the stringified object.
The problem is indeed you cannot sort the values of the properties of an object. So I convert it to an array before binding it:
So,
languageResource.getCultures().then(function(cultures) {
vm.availableCultures = cultures;
});
becomes
languageResource.getCultures().then(function (culturesDictionary) {
var cultures = [];
angular.forEach(culturesDictionary, function (value, key) {
cultures.push({
lcid: key,
name: value
});
});
vm.availableCultures = cultures;
});
Seen this when the key is numerical. If the key's data type is string than it would keep its sorted state after an API call. If the key's data type is numerical, than, you would need set the key's value as a string and even add single quotes before and after the key's value, before the API sends it back.
I haven't tried the approach to stringfy the dictionary in the API. After the call you would parse the string back to an object with something like JSON.parse(string) might be your best bet.

Override sails update to return just one object

When I update a model, waterlock .update() always return an array of objects, even if I set on criteria a primaryKey.
on my code
Ad.update({ id: req.param('id') }, {
// desired attributed to be updated
}).exec(function(err, updatedRecord) {
// updatedRecord is always an array of objects
});
And in order to use the updatedRecord, I have to point out to 0 index like updatedRecord[0] which is something I consider not very clean. According to docs update() in sails, this is a common escenario.
Knowing that, I have 2 questions:
Wouldn't be better that when you find one model return just a updated object for that model, not an array?
If that is a convention, how could be overrided this function in order to return just an object instead of an array when .update() have only affected one record?
it is a convention that it will update all the records that matches the find criteria, but as you are probably using a unique validation on model, it will probably return an array of 1 or 0. You need to do it on hand.
You can override methods in model, by implementing a method with same name as waterline default. But as you will need to completely rewrite the code, it is not viable. Neither changing waterline underlying code.
A solution will be creating a new function on your Ad model:
module.exports = {
attributes: {
adid: {
unique: true,
required: true
},
updateMe: {
}
},
updateOne: function(adid, newUpdateMe, cb){
Ad.update({ id: req.param('id') }, {
// desired attributed to be updated
}).exec(function(err, updatedRecord) {
// updatedRecord is always an array of objects
if (updatedRecord.length == 1){
return cb(null, updatedRecord[0]);
}
return cb(null, {}); //also can error if not found.
});
}
};
Also. Avoid using id as an model attribute (use other name), as some databases like mongodb already add this attribute as default and may cause conflicts with your model.
I dont think its possible with waterline. Its because update method is a generalized one, passing a primary key in where condition is always not the case.

MongoDb subdocument array populate (via Mongoose ORM) : Does it maintain array order when populate is called

Suppose I have 2 Schema's in Mongoose that look like this:
var movieSchema = mongoose.Schema({
name: String,
type: String
});
var moviePlaylistSchema = mongoose.Schema({
name: String,
movies: [{type: mongoose.Schema.Types.ObjectId, ref: 'Movie'}]
});
var Movie = mongoose.model('Movie', movieSchema);
var MoviePlaylist = mongoose.model('MoviePlaylist', moviePlaylistSchema);
If a query was made along the following lines:
MoviePlaylist.find({}).populate('movies').exec(function(err, res) {
if (err) console.log('err', err);
else {
console.log('res', res);
res.forEach(function(elem, index) {
console.log('elem.name', elem.name);
});
}
});
Would the order of the elements in the array be maintained? The objective here is to allow the user to maintain a playlist order of their movies. If, when the "populate" method fires, the array order of Movie object Ids is not maintained, then this will not serve my purpose. Hence thought I'd ask someone who is more knowledgeable in this area.
If this works, then I have another task which is allowing the user to change the order of movies in the playlist, which should be straight forward by allowing the movie object id index to be swapped in the array.
Thanks for your help in advance.
MongoDB will keep the order of the array, much like an array in any programming language.
You can view the BSON/JSON spec for reference which highlights that the array must contain integer values for keys, and be maintained in ascending numerical order.
Additionally, the Mongoose populate on an array works by calling Model.populate via forEach on each element of the array. This modifies the array in place, hence the order is preserved. You can see the relevant source code here.

How do i get the specific value from json data using Angularjs

i am new to AngularJs. I am trying to get the values from json based on search key word and displaying that related data.
Below is my json format
{"abc":[
{ "url":"abc.json"}
],
"bbc":[
{"url":"bbc.json"}
]
}
i am comparing the key with entered search word. If it matches then i need to load the separate json which is related to found key. I am able to compare the search word with key, but when i am trying to get the value am getting total value like url=abc.json, instead of this i've to get only abc.json. My controller code is as follows
function getDetailsController($scope,$http) {
$scope.search = function() {
$http.get("searchInfo.json").success(function(response) {
angular.forEach(response, function(value, key) {
if(angular.equals(key, $scope.searchText)){
$scope.url = value;
$http.get(url).success(function(response) {
$scope.details = response;
});
}
});
});
};
}
I have tried in diffrent ways but i was not able to get the value. Could you please help me on this.
In your JSON, '"abc"': is a key, and its corresponding value is
[{ "url":"abc.json"}]
That is an array containing a single object, the object containing a single key: "url".
So, to access this URL, you simply need
value[0].url
This structure is quite strange though. I don't really understand the point of wrapping the object inside an array.

Resources