Mongoose querying the array... changing the elements of the array - arrays

I am trying to remove all the elements from the array in the MongoDB database, then I insert all the new array elements.
My Model is:
const mongoose = require('mongoose');
var schema = new mongoose.Schema({
email : {
type : String
},
password : {
type : String
},
stocks : {
type : [String]
}
}, {versionKey:false}, {_id: false});
module.exports = final = mongoose.model('users', schema);
My stocks array will then have some values. I am trying to remove those values using the following command:
I read at somewhere in Stack Overflow that to empty your array you can do many things but a set is the fastest way to do this. Please let me know if you know any other way which is better than this.
final
.findOneAndUpdate({email:"abcd#gmail.com"}, {$set:{stocks:[]}})
.then(()=>console.log("Data removed."))
.catch(err=>console.log(err));
Once data is removed it means the array will get emptied. Then I assign the whole set of the new array from my local variable like this:
const newData = {
stocks : ["abcd", "wxyz"]
};
Now I am trying to assign this new array to my database using this command:
final
.findOneAndUpdate({email:"abcd#gmail.com"}, {$set:{stocks:newData.stocks}});
It is emptying the array successfully, but when I am assigning new array it is not working and shows an empty array. Can anyone assist me with this, please?

Try with
final.findOneAndUpdate({email:"abcd#gmail.com"}, {$set:{stocks:newData.stocks}}, {new: true})
.then((doc)=>console.log(doc))
.catch(err=>console.log(err));
If you don't use a callback the query is not executed.
The query executes if callback is passed else a Query object is returned.
Mongoose documentation

Related

Sorting in mongoose Express does not sort properly

I need help with sorting in Express working with mongooose db.
When i use sort({'price':1}) everythink is good, but when i pass JSON.stringify(sort) which contains and logs out {"price":1} it stops working. Any ideas why?
if(req.query.sortOption){
const str = req.query.sortOption.split(':');
sort[str[0]] = str[1] === 'desc' ? -1:1;
}
console.log(JSON.stringify(sort));
//here logs out {"price":-1} which works when i pass it into sort function as a string
try {
const annoucements = await Annoucement.find(query)
.skip(page * annoucementsPerPage)
.limit(annoucementsPerPage)
.populate('author')
.sort(JSON.stringify(sort))
res.status(200).json({
status: 'Successfully got an annoucement',
results: annoucements.length,
data: {
annoucements,
},
});
} catch (error) {
res.status(500).json({
status: 'Failed to get all annoucements',
message: error,
});
}
};
How to sort in mongoose?
.sort() takes in an object, and does not take in a string. You used JSON.stringify(sort), which made the sort query into a string, hence mongoose could not parse it.
Solution:
You should just pass .sort(sort) instead of transforming the object to a string.
Explanation:
Mongoose either accepts
a string like "price" (for ascending order) or "-price" (for descending order).
an array (not applicable in this case)
an object, where the key is the property name and the value is the order (1, "asc", "ascending" or -1, '"desc", "descending"`)
What you did was basically pass the string value "{price:-1}" to it, which does not match any of the use cases. Therefore your sorting does not work as expected.

How to pass an Encoded ("application/x-www-form-urlencoded") object with array within a query string in HttpClient?

I am trying to encode ("application/x-www-form-urlencoded") an object in Angular using HttpParameterCodec.
This object has a field as object which in turn has array of string. object structure as mentioned below.
export class SearchRequest {id: string = undefined;partnerIds: PartnerIds = undefined;}
export class PartnerIds { partnerId: string[] = undefined;}
Now when I am trying encode this object with utility code (which works fine with plain object) mentioned below, It is not in correct format due to list of string in it.
generateQueryParams(searchRequest) {
let httpParams: HttpParams = new HttpParams({encoder: new CustomEncoderComponent()});
Object.keys(searchRequest).forEach(key => {
httpParams = httpParams.append(key, searchRequest[key]);
});
return httpParams;
}
I tried with below query params format but it did not work.
1. id=123&partnerIds=XYZ&partnerIds=ABC
2. id=123&partnerId[]=XYZ&partnerId[]=ABC
3. id=123&partnerId=XYZ&partnerId=ABC
Please suggest How to pass this (SearchRequest) object within a query string in HttpClient?

How to check an array with regular expression in GraphQL

I need to check the existence of some elements in an array as such
I have an array as such
ar = ['one','two','three']
I want to know how I can individually check the elements in the regular expression code below instead of "/something/" that would map through my array and check if they exist in graphQL one by one.
similar : allCockpitHello (filter: {Association : {value : {regex: "\/something/" }}} limit:2){
nodes{
Name{
value
}
}
You need to have the regex string as an input parameter to be used by the resolver, GraphQL is not going to do the filter for you, you need to do/call that logic in the resolver based on your inputs.
Based on your example, you could have something like this on the schema and resolver:
type Node {
name: String!
}
type NodeQueries {
nodes (filterRegEx :String): [Node]!
}
Once you have the input string on the resolver, the implementation of the filter mechanism is up to you.
const resolvers = {
...
NodeQueries: {
nodes: (parent, params) => {
const {filterRegEx} = params; // regex input string
const ar = ['one','two','three'];
// Create a RegExp based on the input,
// Compare the with the elements in ar and store the result...
// You might end up with ... res = ['one', 'three'];
// Now map the result to match your schema:
return _.map(res, name => ({name}) ); // to end up with [{name: 'one'}, {name: 'three'}]
}
}
...
}
GraphQL is not a magic bullet - it's only a query language, it 'transports' your needs to the engine (local client, remote server ...) where all the necessary processing takes place.
In this case you probably need to pass your array and expression as variables to the server (resolver). If processing is expensive results (similar relation) should be already defined, cached, preprocessed, etc.
If dataset is small you can do this entirely client-side - iterate over an array (fetched using graphql).

getting data from an object's array with vue.js

I am trying to access the following data in Vue.js
{"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}
self.player = response.name works. now i need self.point
methods: {
fetchData: function() {
var self = this;
$.get("api/v1/players/1", function(response) {
console.log(response);
self.player = response.name;
self.point = response.stats.points
});
}
}
I have thus far tried response.stats["points"], response.stats[2], response.stats[ { points } ], response.stats[points]
The stats property in your json holds an array in which the first object has a property named points
So use response.stats[0].points
Keep in mind though that the stats is probably an array for a reason. It might hold more than one objects in the future, so always using the first element [0] might not be a valid approach.
I think it can help you
var json = JSON.parse(data);
json.stats[0].points
response = {"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}
If you want to access the name
console.log(response.name) // Westbrook
If you want to access the stats data which contain list, simply target
let stats=response.stats[0] //By getting the first index in the list
Get the points in stats
console.log(stats.points) // 2588

Angularjs - How to store objects in an array and local storage

How I can store multiple objects into an array and then into local storage so that I can get all objects when required using a loop.
example objects:
var newMsg = {
sentDate: msgDate,
sentTime: msgTime,
msgTitle: "message title",
msgDesc: "message desc"
};
Currently I'm using https://github.com/grevory/angular-local-storage#configuration-example angularjs module but struggling to store and retrieve objects from an array.
I have tried the following code:
msgArray = [];
var savedMsgs = localStorageService.set("wimmtkey", newMsg);
msgArray.push(savedMsgs);
console.log(savedMsgs);
This outputs 'true' in the console but expecting to see the stored object. Please also advise to loop through the array to retrieve the objects. Thanks.
Some more code would be useful but for angular-local-storage this is the way that you push objects into array before saving the array in the localStorage:
var msgArray = [];
var newMsg = {
sentDate: msgDate,
sentTime: msgTime,
msgTitle: "message title",
msgDesc: "message desc"
};
//you can push all the objects here before saving to the storage
//maybe you have a forEach here, pushing the objects? Who knows
msgArray.push(newMsg);
//the array is now set in the storage
localStorageService.set("wimmtkey", msgArray);
//the array obtained from local storage
var obtained_array = localStorageService.get("wimmtkey");

Resources