MongoDB search nested objects in an array - laravel

I am using MongoDB to store all the events in my Eventbrite clone. So I have a collection called events then the objects in this collection consists of their name and and array of users that have rsvp to the event. I can query for any events that the current user has created but unable to figure out how to query both events the user has created and rsvp to.
Here is the compiled query that I am using to try to get all the users events.
events.find({"$and":[{"user_id":"5d335704802df000076bad97"},{"user_id":{"$ne":null}}],"$or":[{"checkins.user_id":"5d335704802df000076bad97"}]},{"typeMap":{"root":"array","document":"array"}})
I am using the Laravel MongoDB plugin to query my data in php it looks like this
$user->events()->orWhere(function ($query) use ($user){
return $query->where('checkins.user_id',new ObjectID($user->id));
})->get()
The event object looks something like this:
{
"name": "test",
"user_id": "1"
"rsvp": [
{"user_id": "12"}
]
}
An user can rsvp to other event that are not their own.

you need an $or filter and $elemMatch to get events that belong to a given user or events they've rsvp'd to.
db.events.find({
"$or": [
{
"user_id": "5d33e732e1ea9d0d6834ef3d"
},
{
"rsvp": {
"$elemMatch": {
"user_id": "5d33e732e1ea9d0d6834ef3d"
}
}
}
]
})
unfortunately i can't help you with laravel version of the query. in case it helps, below is the c# code that generated the above mongo query.
using MongoDB.Entities;
using System.Linq;
namespace StackOverflow
{
public class Program
{
public class user : Entity
{
public string name { get; set; }
}
public class Event : Entity
{
public string name { get; set; }
public string user_id { get; set; }
public rsvp[] rsvp { get; set; }
}
public class rsvp
{
public string user_id { get; set; }
}
private static void Main(string[] args)
{
new DB("test");
var mike = new user { name = "mike" };
var dave = new user { name = "dave" };
mike.Save();
dave.Save();
(new[] {
new Event
{
name = "mike's event",
user_id = mike.ID,
rsvp = new[]
{
new rsvp { user_id = dave.ID }
}
},
new Event
{
name = "dave's event",
user_id = dave.ID,
rsvp = new[]
{
new rsvp { user_id = mike.ID }
}
}
}).Save();
var result = DB.Find<Event>()
.Many(e =>
e.user_id == mike.ID ||
e.rsvp.Any(r => r.user_id == mike.ID));
}
}
}

Related

Elasticsearch - NEST - Upsert

I have the following two classes
Entry
public class Entry
{
public Guid Id { get; set; }
public IEnumerable<Data> Data { get; set; }
}
EntryData
public class EntryData
{
public string Type { get; set; }
public object Data { get; set; }
}
I have a bunch of different applications that produces messages to a queue that I then consume in a separate application to store that data in elasticsearch.
Im using a CorrelationId for all the messages and I want to use this ID as the ID in elasticsearch.
So given the following data:
var id = Guid.Parse("1befd5b62b944b4aa600c85632159e11");
var entries = new List<Entry>
{
new Entry
{
Id = id,
Data = new List<EntryData>
{
new EntryData
{
Data = DateTime.UtcNow,
Type = "APPLICATION1_Received"
},
new EntryData
{
Data = DateTime.UtcNow,
Type = "APPLICATION1_Validated"
},
new EntryData
{
Data = DateTime.UtcNow,
Type = "APPLICATION1_Published"
},
}
},
new Entry
{
Id = id,
Data = new List<EntryData>
{
new EntryData
{
Data = DateTime.UtcNow,
Type = "APPLICATION2_Received"
},
new EntryData
{
Data = DateTime.UtcNow,
Type = "APPLICATION2_Validated"
},
new EntryData
{
Data = DateTime.UtcNow,
Type = "APPLICATION2_Published"
},
}
},
new Entry
{
Id = id,
Data = new List<EntryData>
{
new EntryData
{
Data = DateTime.UtcNow,
Type = "APPLICATION3_Received"
},
new EntryData
{
Data = DateTime.UtcNow,
Type = "APPLICATION3_Validated"
},
new EntryData
{
Data = DateTime.UtcNow,
Type = "APPLICATION3_Published"
},
}
},
};
I want this to be saved as one entry in elasticsearch where ID == 1befd5b6-2b94-4b4a-a600-c85632159e11 and a data array that contains 9 elements.
Im struggling a bit with getting this to work, when trying the following:
var result = await _elasticClient.BulkAsync(x => x.Index("journal").UpdateMany(entries, (descriptor, entry) => {
descriptor.Doc(entry);
return descriptor.Upsert(entry);
}), cancellationToken);
But this is just overwriting whatever already exists in the data array and the count is 3 instead of 9 (only the Application3 entries are saved).
So, is it possible to do what I want to do? I never worked with elasticsearch before so it feels like maybe Im missing something simple here... :)
Managed to solve it like this:
var result = await _elasticClient.BulkAsync(x => x.Index("journal").UpdateMany(entries, (descriptor, entry) => {
var script = new InlineScript("ctx._source.data.addAll(params.data)")
{
Params = new Dictionary<string, object> {{"data", entry.Data}}
};
descriptor.Script(b => script);
return descriptor.Upsert(entry);
}), cancellationToken);

$select on navigation property / WebApi 2.0 / OData 4

Given the following simple OData 4 controller (please see below), how do I $select just the cities?
http://localhost//api/Customers?$select=Location
Gives me:
{
"#odata.context":"http://localhost/api/$metadata#Customers(Location)","value":[
{
"Location":{
"Country":"Ireland","City":"Sligo"
}
},{
"Location":{
"Country":"Finland","City":"Helsinki"
}
}
]
}
But I don't know how to drill down one deeper so that I just get the cities. Is this even possible?
public class CustomersController : ODataController
{
private List<Customer> customers = new List<Customer>()
{
new Customer
{
CustomerId = 1,
Location = new Address
{
City = "Sligo",
Country = "Ireland"
}
},
new Customer
{
CustomerId = 2,
Location = new Address
{
City = "Helsinki",
Country = "Finland"
}
}
};
[EnableQuery]
public List<Customer> Get()
{
return customers;
}
}
The grammar for $select does not allow a path expression like Location/City. Your best bet is to define an OData function bound to the Customers entity set. E.g.,
[HttpGet]
public IEnumerable<string> GetCities()
{
return customers.Select(c => c.Location.City);
}
And invoke it as follows:
GET http://localhost/api/Customers/ServiceNamespace.GetCities

Can I display contents of Application or Cache objects using Glimpse in an MVC project?

The ASP.NET WebForms trace output has a section for Application State. Is it possible to see the same using Glimpse?
In my home controller's Index() method, I tried adding some test values, but I don't see the output in any of the Glimpse tabs.
ControllerContext.HttpContext.Application.Add("TEST1", "VALUE1");
ControllerContext.HttpContext.Cache.Insert("TEST2", "VALUE2");
I didn't see anything in the documentation either.
I don't think that there is an out-of-the-box support for this, but it would be trivial to write a plugin that will show this information.
For example to show everything that's stored in the ApplicationState you could write the following plugin:
[Glimpse.Core.Extensibility.GlimpsePluginAttribute]
public class ApplicationStateGlimpsePlugin : IGlimpsePlugin
{
public object GetData(HttpContextBase context)
{
var data = new List<object[]> { new[] { "Key", "Value" } };
foreach (string key in context.Application.Keys)
{
data.Add(new object[] { key, context.Application[key] });
}
return data;
}
public void SetupInit()
{
}
public string Name
{
get { return "ApplicationState"; }
}
}
and then you get the desired result:
and to list everything that's stored into the cache:
[Glimpse.Core.Extensibility.GlimpsePluginAttribute]
public class ApplicationCacheGlimpsePlugin : IGlimpsePlugin
{
public object GetData(HttpContextBase context)
{
var data = new List<object[]> { new[] { "Key", "Value" } };
foreach (DictionaryEntry item in context.Cache)
{
data.Add(new object[] { item.Key, item.Value });
}
return data;
}
public void SetupInit()
{
}
public string Name
{
get { return "ApplicationCache"; }
}
}

Problems with MVC 3 DropDownList() in WebGrid()

I'm trying to place a DropDownList inside a WebGrid but I can't figure out how to do it :(
Things I've tried:
grid.Column("Id", "Value", format: ((item) =>
Html.DropDownListFor(item.SelectedValue, item.Colors)))
and
grid.Column(header: "", format: (item => Html.DropDownList("Colors", item.Colors)))
and
grid.Column(header: "", format: Html.DropDownList("Colors"))
and various others but I couldn't get it to work.
Any help is much appreciated.
Model
public class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public SelectList Colors { get; set; }
public int SelectedValue { get; set; }
}
public class ColorViewModel
{
public int ColorID { get; set; }
public string ColorName { get; set; }
}
Controller
public ActionResult Index()
{
var colorList = new List<ColorViewModel>() {
new ColorViewModel() { ColorID = 1, ColorName = "Green" },
new ColorViewModel() { ColorID = 2, ColorName = "Red" },
new ColorViewModel() { ColorID = 3, ColorName = "Yellow" }
};
var people = new List<PersonViewModel>()
{
new PersonViewModel() {
Name = "Foo",
Age = 42,
Colors = new SelectList(colorList)
},
new PersonViewModel() {
Name = "Bar",
Age = 1337,
Colors = new SelectList(colorList)
}
};
return View(people);
}
View
#model IEnumerable<PersonViewModel>
#{
var grid = new WebGrid(Model);
}
<h2>DropDownList in WebGrid</h2>
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Age"),
grid.Column() // HELP - INSERT DROPDOWNLIST
)
)
<p>
<button>Submit</button>
</p>
}
grid.Column(
"dropdown",
format: #<span>#Html.DropDownList("Color", (SelectList)item.Colors)</span>
)
Also in your controller make sure you set the value and text properties of your SelectList and instead of:
Colors = new SelectList(colorList)
you should use:
Colors = new SelectList(colorList, "ColorID", "ColorName")
Also it seems a bit wasteful to me to define the same SelectList for all row items especially if they contain the same values. I would refactor your view models a bit:
public class MyViewModel
{
public IEnumerable<SelectListItem> Colors { get; set; }
public IEnumerable<PersonViewModel> People { get; set; }
}
public class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public int SelectedValue { get; set; }
}
and then:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// define the values used to render the dropdown lists
// for each row
Colors = new[]
{
new SelectListItem { Value = "1", Text = "Green" },
new SelectListItem { Value = "2", Text = "Red" },
new SelectListItem { Value = "3", Text = "Yellow" },
},
// this is the collection we will be binding the WebGrid to
People = new[]
{
new PersonViewModel { Name = "Foo", Age = 42 },
new PersonViewModel { Name = "Bar", Age = 1337 },
}
};
return View(model);
}
}
and in the view:
#model MyViewModel
#{
var grid = new WebGrid(Model.People);
}
<h2>DropDownList in WebGrid</h2>
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Age"),
grid.Column(
"dropdown",
format: #<span>#Html.DropDownList("Color", Model.Colors)</span>
)
)
)
<p>
<button>Submit</button>
</p>
}
UPDATE:
And since I suspect that you are not putting those dropdownlists for painting and fun in your views but you expect the user to select values inside them and when he submits the form you might wish to fetch the selected values, you will need to generate proper names of those dropdown lists so that the default model binder can automatically retrieve the selected values in your POST action. Unfortunately since the WebGrid helper kinda sucks and doesn't allow you to retrieve the current row index, you could use a hack as the Haacked showed in his blog post:
grid.Column(
"dropdown",
format:
#<span>
#{ var index = Guid.NewGuid().ToString(); }
#Html.Hidden("People.Index", index)
#Html.DropDownList("People[" + index + "].SelectedValue", Model.Colors)
</span>
)
Now you could have a POST controller action in which you will fetch the selected value for each row when the form is submitted:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// the model variable will contain the People collection
// automatically bound for each row containing the selected value
...
}
..make my dropdown list to select a value from the list when it loads.The following works for sure. I have tried it out myself. Any questions keep me posted.
#Html.DropDownList("RejectReason", Model.SalesReasonList.Select(u => new SelectListItem
{
Text = u.Text,
Value = u.Value,
Selected = u.Value ==#item.RejectReason
}))

Populating child drop down based on what was selected from parent drop down list

I am using the latest version of jQuery and ASP.NET MVC 3 with the Razor view engine.
I have tried Google looking for a decent example of loading a child drop down list when a parent drop down item is selected. I am looking to do this via jQuery AJAX using JSON. My knowledge of this is zero.
I have a Category class with a list of categories. It's a parent-child association.
If I select a category from the parent drop down list, then all the child categories need to be listed in the child drop down list for the selected parent category.
This is what I currently have, but need to complete it, not sure if I am in the right direction:
$(document).ready(function () {
$('#ddlParentCategories').change(function () {
alert('changed');
});
});
I loaded my drop down list from my view model as such:
#Html.DropDownListFor(x => x.ParentCategoryId, new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId), "-- Select --", new { id = "ddlParentCategories" })
The first item has text "-- Select --" (for both parent and child drop down lists). On initial page load nothing must be loaded in the child drop down list. When a value is selected then the child drop down list must be populated. And when "-- Select --" is selected again in the parent drop down list then all the items in the child drop down list must cleared except "-- Select --".
If possible, if the child categories is loading, how do I display that "round" loading icon?
UPDATE
I have updated my code to Darin's code, and I cannot get it to work properly:
Category class:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public bool IsActive { get; set; }
public int? ParentCategoryId { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
}
EditProductViewModel class:
public class EditProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
public bool IsActive { get; set; }
public string PageTitle { get; set; }
public bool OverridePageTitle { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public int ParentCategoryId { get; set; }
public IEnumerable<Category> ParentCategories { get; set; }
public int ChildCategoryId { get; set; }
public IEnumerable<Category> ChildCategories { get; set; }
}
ProductController class:
public ActionResult Create()
{
EditProductViewModel viewModel = new EditProductViewModel
{
ParentCategories = categoryService.GetParentCategories()
.Where(x => x.IsActive)
.OrderBy(x => x.Name),
ChildCategories = Enumerable.Empty<Category>(),
IsActive = true
};
return View(viewModel);
}
public ActionResult AjaxBindingChildCategories(int parentCategoryId)
{
IEnumerable<Category> childCategoryList = categoryService.GetChildCategoriesByParentCategoryId(parentCategoryId);
return Json(childCategoryList, JsonRequestBehavior.AllowGet);
}
Create view:
<tr>
<td><label>Parent Category:</label> <span class="red">*</span></td>
<td>#Html.DropDownListFor(x => x.ParentCategoryId,
new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId),
"-- Select --",
new { data_url = Url.Action("AjaxBindingChildCategories"), id = "ParentCategories" }
)
#Html.ValidationMessageFor(x => x.ParentCategoryId)
</td>
</tr>
<tr>
<td><label>Child Category:</label> <span class="red">*</span></td>
<td>#Html.DropDownListFor(x => x.ChildCategoryId,
new SelectList(Model.ChildCategories, "Id", "Name", Model.ChildCategoryId),
"-- Select --",
new { id = "ChildCategories" }
)
#Html.ValidationMessageFor(x => x.ChildCategoryId)
</td>
</tr>
<script type="text/javascript">
$(document).ready(function () {
$('#ParentCategories').change(function () {
var url = $(this).data('url');
var data = { parentCategoryId: $(this).val() };
$.getJSON(url, data, function (childCategories) {
var childCategoriesDdl = $('#ChildCategories');
childCategoriesDdl.empty();
$.each(childCategories, function (index, childCategory) {
childCategoriesDdl.append($('<option/>', {
value: childCategory, text: childCategory
}));
});
});
});
});
</script>
It goes into my AjaxBindingChildCategories action and it brings back records, it just doesn't want to display my child category dropdownlist. I had a look in Fire Bug and the error that I get is:
GET AjaxBindingChildCategories?parentCategoryId=1
500 Internal Server Error
Here's an example of cascading drop down lists. As always start by defining a view model:
public class MyViewModel
{
[DisplayName("Country")]
[Required]
public string CountryCode { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
public string City { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: Fetch countries from somewhere
Countries = new[]
{
new SelectListItem { Value = "FR", Text = "France" },
new SelectListItem { Value = "US", Text = "USA" },
},
// initially we set the cities ddl to empty
Cities = Enumerable.Empty<SelectListItem>()
};
return View(model);
}
public ActionResult Cities(string countryCode)
{
// TODO: based on the selected country return the cities:
var cities = new[]
{
"Paris", "Marseille", "Lyon"
};
return Json(cities, JsonRequestBehavior.AllowGet);
}
}
a view:
#model MyViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.CountryCode)
#Html.DropDownListFor(
x => x.CountryCode,
Model.Countries,
"-- Select country --",
new { data_url = Url.Action("cities") }
)
#Html.ValidationMessageFor(x => x.CountryCode)
</div>
<div>
#Html.LabelFor(x => x.City)
#Html.DropDownListFor(
x => x.City,
Model.Cities,
"-- Select city --"
)
#Html.ValidationMessageFor(x => x.City)
</div>
<p><input type="submit" value="OK" /></p>
}
and finally the unobtrusive javascript in a separate file:
$(function () {
$('#CountryCode').change(function () {
var url = $(this).data('url');
var data = { countryCode: $(this).val() };
$.getJSON(url, data, function (cities) {
var citiesDdl = $('#City');
citiesDdl.empty();
$.each(cities, function (index, city) {
citiesDdl.append($('<option/>', {
value: city,
text: city
}));
});
});
});
});
jQuery script will look like this:
<script type="text/javascript">
function getCities(abbr) {
$.ajax({
url: "#Url.Action("Cities", "Locations")",
data: {abbreviation: abbr},
dataType: "json",
type: "POST",
error: function() {
alert("An error occurred.");
},
success: function(data) {
var items = "";
$.each(data, function(i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#City").html(items);
}
});
}
$(document).ready(function(){
$("#State").change(function() {
var abbr = $("#State").val();
getCities(abbr);
});
});
</script>
A repository to retrieve data could look like this (obviously hook it up to live data though):
public class LocationRepository : ILocationRepository
{
public IQueryable<State> GetStates()
{
return new List<State>
{
new State { Abbreviation = "NE", Name = "Nebraska" },
new State { Abbreviation = "NC", Name = "North Carolina" }
}.AsQueryable();
}
public IQueryable<City> GetCities(string abbreviation)
{
var cities = new List<City>();
if (abbreviation == "NE")
{
cities.AddRange(new List<City> {
new City { Id = 1, Name = "Omaha" },
new City { Id = 2, Name = "Lincoln" }
});
}
else if (abbreviation == "NC")
{
cities.AddRange(new List<City> {
new City { Id = 3, Name = "Charlotte" },
new City { Id = 4, Name = "Raleigh" }
});
}
return cities.AsQueryable();
}
}
public interface ILocationRepository
{
IQueryable<State> GetStates();
IQueryable<City> GetCities(string abbreviation);
}
Controllers could look like this:
public class LocationsController : Controller
{
private ILocationRepository locationRepository = new LocationRepository();
[HttpPost]
public ActionResult States()
{
var states = locationRepository.GetStates();
return Json(new SelectList(state, "Id", "Name"));
}
[HttpPost]
public ActionResult Cities(string abbreviation)
{
var cities = locationRepository.GetCities(abbreviation);
return Json(new SelectList(cities, "Abbreviation", "Name"));
}
}
I am assuming you populate the parent dropdown from server side and also the first option in this parent dd is "--- Select ---"
You can try this
$(document).ready(function () {
var $parent = $('#ddlParentCategories');
var $child = $('#ddlChildCategories');
$child.find("option:gt(0)").remove();
if(!$parent.children().eq(0).is(":selected")){
$parent.change(function () {
$.ajax({
url: "urlToFetchTheChild",
data: { categoryId: this.value },
success: function(data){
//The data you send should be a well formed array of json object containing code/value pair of child categories
for(var i = 0;i<data.length;i++){
$child.append("<option value='"+ data[i].code +"'>"+ data[i].value +"</option>");
}
}
});
});
}
});

Resources