Here is my schema (simple schema):
officelocation: {
type: String,
label: 'Location of Office',
autoform: {
type: 'map',
afFieldInput: {
type: 'map',
geolocation: true,
searchBox: true,
autolocate: true
}
}
},
location: {
optional: true,
type: 'Point'
}
My server side js code is below (note this is in a collection.after hook) so I want to update it based on the address that user has entered, which I have resolved into lat long:
Providers.update({_id: doc._id}, {$set: {location: {type:"Point", coordinates:[lng,lat]} } });
When I see the file in the collection (db.providers.find();), I see the below.. Note that the location embedded object is empty:
{ "_id" : "X8ZfKYJAP9cduwvmd", "phone" : 999999999, "officelocation" : "40.7192714,14.872363899999982", "createdAt" : ISODate("2015-04-24T02:00:40.447Z"), "updatedAt" : ISODate("2015-04-24T02:00:40.799Z"), "owner" : "GB4TxTHodkykeeXp6", "officeaddress" : "Via Califri, 5, 84099 San Cipriano Picentino SA, Italy", "location" : { } }
I am basically trying to make sure by collections are stored in a geo-spatial-searchable way, but this approach does not seem to work. Any help?
There could be a number of things causing your update to fail, from allow-deny rules to Simple Schema cleaning out your data.
I see that you are using a custom type to store your location. Make sure you have used a Transform to ensure the type isn't lost on the way to the server. From the Simple Schema readme:
Custom object types are treated as blackbox objects by default. However, when using collection2, you must ensure that the custom type is not lost between client and server. This can be done with a transform function that converts the generic Object to the custom object. Without this transformation, client-side inserts and updates might succeed on the client but then fail on the server. Alternatively, if you don't care about losing the custom type, you can explicitly set blackbox: true for a custom object type instead of using a transformation.
Alternatively you could use a sub-schema to define what a location is allowed to look like, instead of using a custom type, but it won't keep the methods of the Point type.
Related
We are using AWS Amplify. This is my type
type Package #model {
id: ID!
desc: String!
company: Company! #connection
servicetype: ServiceType! #connection
price: Float!
active: Boolean!
createdAt: AWSDateTime
updatedAt: AWSDateTime
}
Amplify does not generate a filter option for listPackage to allow filtering on servicetype. My understanding is you need to add a custom query and resolver for this. I have added a query listPackageByServiceType but am confused on the resolver... cannot get it to work.
Is there a similar example of code I can follow? I cannot get the filter option to work correctly.
If you have a secondary index on your DynamoDB table based on that field, serviceType, you can do this with a query on that field.
Otherwise, the way to go is probably a scan with a filter on that field. See here for more: https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html#aws-appsync-resolver-mapping-template-reference-dynamodb-scan
From that link, the scan mapping template would look like this (note that depending on what you have, pagination might be necessary):
{
"version" : "2017-02-28",
"operation" : "Scan",
"index" : "fooIndex",
"filter" : {
"expression" : "filter expression"
"expressionNames" : {
"#name" : "name",
},
"expressionValues" : {
":value" : ... typed value
}
}
}
I made a beer matching dating app for a school assignment. Unfortunately am I having a bit of trouble finding out how to search in my database on a template injected number as object.
I've tried this I read on MongoDB docs
The database looks like this :
beerProfile: Object
↳24589: Object
↳name: "Heineken"
img: "https://untappd.akamaized.net/site/beer_logos/beer94130_52756_sm.jpeg"
description: "Heinken is a beer"
bid:"24589"
So beerProfile is an object and has the object 24589 inside it. Inside the 24589 object are name, imd, description and bid.
I tried to use the find() function. ( the collection is called users )
db.collection('users').find( { [24589]: [{name: [Heineken]}] }, { name: 1, bid: 1 }, done);
And I also tried :
db.collection('users').find( { $text: { $search: 24589 } }, done);
I would like to make it return the object values of the 24589 object. Does anyone how I can achieve this ?
I think your "schema" became unnecessarily complex by using a variable (24589) as a key. You should change it to something like this:
beerProfile: Object
↳beer: Object
↳name: "Heineken"
img: "https://untappd.akamaized.net/site/beer_logos/beer94130_52756_sm.jpeg"
description: "Heinken is a beer"
bid:"24589"
Then you can use a simple find():
db.collection('users').find( { "beer.bid": "24589"})
In my Stacks schema i have a dimensions property defined as such:
dimensions: {
type: [String],
autoform: {
options: function() {
return Dimensions.find().map(function(d) {
return { label: d.name, value: d._id };
});
}
}
}
This works really well, and using Mongol I'm able to see that an attempt to insert data through the form worked well (in this case I chose two dimensions to insert)
However what I really what is data that stores the actual dimension object rather than it's key. Something like this:
[
To try to achieve this I changed type:[String] to type:[DimensionSchema] and value: d._id to value: d. The thinking here that I'm telling the form that I am expecting an object and am now returning the object itself.
However when I run this I get the following error in my console.
Meteor does not currently support objects other than ObjectID as ids
Poking around a little bit and changing type:[DimensionSchema] to type: DimensionSchema I see some new errors in the console (presumably they get buried when the type is an array
So it appears that autoform is trying to take the value I want stored in the database and trying to use that as an id. Any thoughts on the best way to do this?.
For reference here is my DimensionSchema
export const DimensionSchema = new SimpleSchema({
name: {
type: String,
label: "Name"
},
value: {
type: Number,
decimal: true,
label: "Value",
min: 0
},
tol: {
type: Number,
decimal: true,
label: "Tolerance"
},
author: {
type: String,
label: "Author",
autoValue: function() {
return this.userId
},
autoform: {
type: "hidden"
}
},
createdAt: {
type: Date,
label: "Created At",
autoValue: function() {
return new Date()
},
autoform: {
type: "hidden"
}
}
})
According to my experience and aldeed himself in this issue, autoform is not very friendly to fields that are arrays of objects.
I would generally advise against embedding this data in such a way. It makes the data more difficult to maintain in case a dimension document is modified in the future.
alternatives
You can use a package like publish-composite to create a reactive-join in a publication, while only embedding the _ids in the stack documents.
You can use something like the PeerDB package to do the de-normalization for you, which will also update nested documents for you. Take into account that it comes with a learning curve.
Manually code the specific forms that cannot be easily created with AutoForm. This gives you maximum control and sometimes it is easier than all of the tinkering.
if you insist on using AutoForm
While it may be possible to create a custom input type (via AutoForm.addInputType()), I would not recommend it. It would require you to create a template and modify the data in its valueOut method and it would not be very easy to generate edit forms.
Since this is a specific use case, I believe that the best approach is to use a slightly modified schema and handle the data in a Meteor method.
Define a schema with an array of strings:
export const StacksSchemaSubset = new SimpleSchema({
desc: {
type: String
},
...
dimensions: {
type: [String],
autoform: {
options: function() {
return Dimensions.find().map(function(d) {
return { label: d.name, value: d._id };
});
}
}
}
});
Then, render a quickForm, specifying a schema and a method:
<template name="StacksForm">
{{> quickForm
schema=reducedSchema
id="createStack"
type="method"
meteormethod="createStack"
omitFields="createdAt"
}}
</template>
And define the appropriate helper to deliver the schema:
Template.StacksForm.helpers({
reducedSchema() {
return StacksSchemaSubset;
}
});
And on the server, define the method and mutate the data before inserting.
Meteor.methods({
createStack(data) {
// validate data
const dims = Dimensions.find({_id: {$in: data.dimensions}}).fetch(); // specify fields if needed
data.dimensions = dims;
Stacks.insert(data);
}
});
The only thing i can advise at this moment (if the values doesnt support object type), is to convert object into string(i.e. serialized string) and set that as the value for "dimensions" key (instead of object) and save that into DB.
And while getting back from db, just unserialize that value (string) into object again.
My Mongoose schema:
// set up the schema
var CategorySubSchema = new Schema({
name: { type: String },
_category_main : { type: String, ref: 'CategoryMain' }
},
And my controller code:
CategorySub.create({
name : req.body.name,
_category_main : req.body.category_main
}, function(err, data){
An entry in my db:
{
"_id": "54dd163434d78ae58f6b1a69",
"name": "Snacks",
"_category_main": "54dcf4a71dfecb4d86ddcb87",
"__v": 0
},
So I used an underscore, because I was following an example. Does this mean anything to the database or is it just convention for references?
Also, instead of passing the entire JSON object in the request - req.body.category_main, why not just pass and id and change my schema to this?:
var CategorySubSchema = new Schema({
name: { type: String },
category_main_id : { type: String }
},
In short, Yes.
The below schema definition is an example of Manual references.
var CategorySubSchema = new Schema({
name: { type: String },
category_main_id : { type: String }
}
where,
you save the _id field of one document in another document as a
reference. Then your application can run a second query to return the
related data. These references are simple and sufficient for most use
cases.
In this case, we need to write explicit application code to fetch the referred document and resolve the reference. Since the driver that we use wouldn't know about the collection in which the referred document is present nor the database in which the referred document is present.
When you define the schema as below, this is an example of storing the details of the referred document .(Database references)
var CategorySubSchema = new Schema({
name: { type: String },
_category_main : { type: String, ref: 'CategoryMain' }
}
They include the name of the collection, and in some cases the
database name, in addition to the value from the _id field.
These details allow various drivers to resolve the references by themselves, since the name of the collection and the database(optional) of the referred document would be contained in the document itself, rather than we writing explicit application code to resolve the references.
So I used an underscore, because I was following an example. Does this mean anything to the database or is it just convention for
references?
Using underscore in the _id field is a valid naming convention, but mongoDb doesn't explicitly mention about the naming convention of other fields which are used to resolve references. You could just use any other field name as long as it conforms to this.
Using Mongo and Meteor with CoffeeScript, I'm trying to save a document with one Object:
Test = new SimpleSchema(
tag:
type: Object
)
And the insert:
test1 = new Meteor.Collection("test", { schema: Test})
test1.insert({ tag: {"name": "campus"} })
Result: a document gets saved in the database but the "tag" field is never set.
Couple of different troubleshooting steps I've taken:
Changing the data type to String works and the "tag" field gets set. However, I want to reference a tag property without having to parse the string every time.
Adding a collection without the schema saves the Object exactly how I want:
test2 = new Meteor.Collection("test2")
test2.insert({ tag: {"name": "campus"} })
EDIT: Fixed using the blackbox: true flag. See below answer for clarification.
Test = new SimpleSchema(
tag:
type: Object
blackbox: true
)
According to SimpleSchema docs, all defined properties must pass validation. So any Object data type without properties is treated as an empty Object unless you add the blackbox: true flag.
Source: http://atmospherejs.com/aldeed/simple-schema#blackbox
If you have a key with type Object, the properties of the object will be validated as well, so you must define all allowed properties in the schema. If this is not possible or you don't care to validate the object's properties, use the blackbox: true option to skip validation for everything within the object.
I use simple schema and create my models of the following way, and I don't have any problem.
Test = new Meteor.Collection("test", {
schema: new SimpleSchema({
ownerId: {
type: String,
},
dateAdd: {
type: Date,
}
})
})
Test.insert({ownerId:"123",dateAdd:"..."})
In Coffee Script
Test = new Meteor.Collection("test",
schema: new SimpleSchema(
ownerId:
type: String
dateAdd:
type: Date
)
)