Mongoose default filter/query params for find() - node.js

If I have a collection of docs such as:
{
type: 'post',
text: 'example',
status: 'private' // or 'public'
}
What kind of middleware or schema config can I use to make sure that by default, Model.find() only returns docs where status != 'private' ?
I don't want to have to have to redundantly query for status != 'private' every single time I query the collection.
Thanks for the help!

You could try implement a wrapper method, e.g findNonPrivate(), to your model which you can then delegate to finding every document with status not equal to "private". Something like this:
var Model = mongoose.model('Model', theSchema);
Model.findNonPrivate = function (q, callback) {
q.status = q.status || {"$ne": "private"};
this.find(q, callback);
}
You could then get what you want with Model.findNonPrivate({}, callback).

Related

How to filter results by multiple query parameters if I don't know beforehand how many query strings I may receive from client side?

I want to send in response some data according to searching by query parameters (using .find function of mongoose) from the client side. What do I need to do is a search according to the parameters received?
What I mean is :
I may receive
localhost:5000/admin/customers?customer_id=1&customer_email=abc#gmail.com
I could have used this code to send results according to this query :
Customer.find({
customer_id = req.query.customer_id,
customer_email = req.query.customer_email,
}, (err,docs)=> {
res.json(docs);
})
or
just
localhost:5000/admin/customers?customer_id=1
I could have used this code to send results according to this query :
Customer.find({
customer_id = req.query.customer_id
}, (err,docs)=> {
res.json(docs);
})
or
may be
localhost:5000/admin/customers?no_of_items_purchased=15
I could have used this code to send results according to this query :
Customer.find({
no_of_items_purchased = req.query.no_of_items_purchased
}, (err,docs)=> {
res.json(docs);
})
But what I want is to use .find function on anything received from query params. Like a general code to achieve this.
PS: Also please help with : "How to filter req.query so it only contains fields that are defined in your schema ?"
You can create a query variable to keep the field that you want to filter.
Suppose that your Customer model structure is:
{
customer_id: ...,
customer_name: ...,
customer_email: ...,
no_of_items_purchased: ...
}
Then your code will be:
let {customer_id, customer_name, customer_email, no_of_items_purchased} = req.query;
let query = {};
if (customer_id != null) query.customer_id = customer_id;
if (customer_name != null) query.customer_name = customer_name;
if (customer_email != null) query.customer_email = customer_email;
if (no_of_items_purchased != null) query.no_of_items_purchased = no_of_items_purchased;
let result = await Customer.find(query);
Just pass request.query as a parameter directly on find method:
Customer.find(request.query)

findOneAndUpdate with Upsert always inserting a new user

I want to do is update a record and insert it if it doesn't exist with mongoose. Here is my code:
module.exports.upsertUser = function(user) {
var options = {userName : 'Ricardo'}
Users.findOneAndUpdate({email: user.email}, options, {upsert:true}).exec();
}
And:
var promise = Users.upsertUser(user);
promise
.then(function(results){
...
}
.catch(function(err){
...
}
When I execute the promise, each time a new user is created with the same email.
I'm not sure if I'm performing the update incorrectly. I've tried it in the same way but with update and it does not work either.
Can you help me? Thanks!
You need to put the return without the exec:
module.exports.upsertUser = function(user) {
var options = {userName : 'Ricardo'}
return Users.findOneAndUpdate({email: user.email}, options, {upsert:true, new: true});
}
var promise = Users.upsertUser(user);
promise.then(function(results){
if(results) {
console.log(results);
} else {
console.log('!results');
}
}.catch(function(err){
...
}
FYI:
The default is to return the unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: {new:true} with the upsert option.
according to your coding what findOneAndUpdate() does is that it finds this document/user's document that you are looking for to edit which in this case what you are using to search for this user's document that you want to edit it's document is with his email. Now your second argument modifies that part of the document that you wanted to modify, but this option has to be attached with some mongodb operators (pay a visit to this link for a list of them: https://docs.mongodb.com/manual/reference/operator/update/) but in your case what you need is the $set operator.so i would modify your code like this:
module.exports.upsertUser = function(user) {
var options =
Users.findOneAndUpdate({email: user.email}, {$set:{
userName : 'Ricardo'
}}, {
returnOriginal: true}).exec();
};
so try the above modification let's see how it works

Using an arbitrary number of query params to filter results in mongoose

I'm building an API using node express and mongodb, with mongoose.
I have a post resource that handles user posts, and would like to be able to perform various queries on the post resource.
For instance I have a functions as that returns all posts as follows:
// Gets a list of Posts
exports.index = function(req, res) {
console.log(req.query);
Post.findAsync()
.then(mUtil.responseWithResult(res))
.catch(mUtil.handleError(res));
};
I looking for a good way of processing any additional query params that might come with the request.
/posts will return all posts, but /posts?user=12 will return posts by user with id 12 and /posts?likes=12 will return posts with 12 or more likes.
How can I check for and apply the these query params to filter and return the results since they may or may not be present.
Thanks ;)
If user=12 means "users with id 12", how does likes=12 mean "likes greater than 12"? You need to be more descriptive with your queries. You can do that by passing an array of objects. Send your query in a way that can be interpreted like this:
var filters = [
{
param: "likes",
type: "greater"
value: 12
},
{
param: "user",
type: "equal",
value: "12"
}]
var query = Post.find();
filters.forEach(function(filter) {
if (filter.type === "equal") {
query.where(filter.param).equals(filter.value);
}
else if (filter.type === "greater") {
query.where(filter.param).gt(filter.value);
}
// etc,,,
})
query.exec(callback);

Canjs model returns undefined after resolved

I cannot find a way to retrieve data from the server and convert them to model instance. I folloed the instructions here but it's still doesn't work.
Here is my setup:
url for the service: services/foo/barOne. The response is : {"calendar":1352793756534,"objectId":"id2"}
The model is defined as follow:
var myModel = can.Model(
model: function(raw) {
newObject = {id:raw.objectId};
return can.Model.model.call(this,newObject);
},
findOne: {
url: 'services/foo/barOne',
datatype: 'json'
}
)
And here is how I use that:
myBar = myModel.findOne()
myBar.then(function() {
console.log("resolved with arguments:",arguments); //[undefined]
})
I put various log and tracked all of function called, the request is correctly done, and the ajax resolved correctly. The model method is also correct and return an object of type Constructor with the right parameters.
But after that, inside the pipe function of canjs, the result is lost (ie, I got the result undefined when d.resolve.apply(d, arguments) is called)
What is wrong with this scenario ?
I am using canJS with jquery version 1.0.7
I don't think you need a custom converter just for changing the id. You can change it by setting the static id property. Try it like this:
var MyModel = can.Model({
id : 'objectId'
}, {
findOne: 'services/foo/barOne'
});
MyModel.findOne({ id : 'test' }).done(function(model) {
console.log(model);
});

Fetch Backbone collection with search parameters

I'd like to implement a search page using Backbone.js. The search parameters are taken from a simple form, and the server knows to parse the query parameters and return a json array of the results. My model looks like this, more or less:
App.Models.SearchResult = Backbone.Model.extend({
urlRoot: '/search'
});
App.Collections.SearchResults = Backbone.Collection.extend({
model: App.Models.SearchResult
});
var results = new App.Collections.SearchResults();
I'd like that every time I perform results.fetch(), the contents of the search form will also be serialized with the GET request. Is there a simple way to add this, or am I doing it the wrong way and should probably be handcoding the request and creating the collection from the returned results:
$.getJSON('/search', { /* search params */ }, function(resp){
// resp is a list of JSON data [ { id: .., name: .. }, { id: .., name: .. }, .... ]
var results = new App.Collections.SearchResults(resp);
// update views, etc.
});
Thoughts?
Backbone.js fetch with parameters answers most of your questions, but I put some here as well.
Add the data parameter to your fetch call, example:
var search_params = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
...
'keyN': 'valueN',
};
App.Collections.SearchResults.fetch({data: $.param(search_params)});
Now your call url has added parameters which you can parse on the server side.
Attention: code simplified and not tested
I think you should split the functionality:
The Search Model
It is a proper resource in your server side. The only action allowed is CREATE.
var Search = Backbone.Model.extend({
url: "/search",
initialize: function(){
this.results = new Results( this.get( "results" ) );
this.trigger( "search:ready", this );
}
});
The Results Collection
It is just in charge of collecting the list of Result models
var Results = Backbone.Collection.extend({
model: Result
});
The Search Form
You see that this View is making the intelligent job, listening to the form.submit, creating a new Search object and sending it to the server to be created. This created mission doesn't mean the Search has to be stored in database, this is the normal creation behavior, but it does not always need to be this way. In our case create a Search means to search the DB looking for the concrete registers.
var SearchView = Backbone.View.extend({
events: {
"submit form" : "createSearch"
},
createSearch: function(){
// You can use things like this
// http://stackoverflow.com/questions/1184624/convert-form-data-to-js-object-with-jquery
// to authomat this process
var search = new Search({
field_1: this.$el.find( "input.field_1" ).val(),
field_2: this.$el.find( "input.field_2" ).val(),
});
// You can listen to the "search:ready" event
search.on( "search:ready", this.renderResults, this )
// this is when a POST request is sent to the server
// to the URL `/search` with all the search information packaged
search.save();
},
renderResults: function( search ){
// use search.results to render the results on your own way
}
});
I think this kind of solution is very clean, elegant, intuitive and very extensible.
Found a very simple solution - override the url() function in the collection:
App.Collections.SearchResults = Backbone.Collection.extend({
urlRoot: '/search',
url: function() {
// send the url along with the serialized query params
return this.urlRoot + "?" + $("#search-form").formSerialize();
}
});
Hopefully this doesn't horrify anyone who has a bit more Backbone / Javascript skills than myself.
It seems the current version of Backbone (or maybe jQuery) automatically stringifies the data value, so there is no need to call $.param anymore.
The following lines produce the same result:
collection.fetch({data: {filter:'abc', page:1}});
collection.fetch({data: $.param({filter:'abc', page:1})});
The querystring will be filter=abc&page=1.
EDIT: This should have been a comment, rather than answer.

Resources