Unclear Mongoose error - coffeescript

I get the following error:
TypeError: Cannot read property 'name' of undefined
at new SchemaArray (/home/campaigns/scheduler/tests/node_modules/mongoose/lib/schema/array.js:40:22)
at Function.interpretAsType (/home/campaigns/scheduler/tests/node_modules/mongoose/lib/schema.js:201:12)
at Schema.path (/home/campaigns/scheduler/tests/node_modules/mongoose/lib/schema.js:162:29)
at Schema.add (/home/campaigns/scheduler/tests/node_modules/mongoose/lib/schema.js:110:12)
at Schema.add (/home/campaigns/scheduler/tests/node_modules/mongoose/lib/schema.js:106:14)
at new Schema (/home/campaigns/scheduler/tests/node_modules/mongoose/lib/schema.js:38:10)
at Object. (/home/campaigns/scheduler/tests/testSchedulerModel.coffee:12:21)
at Object. (/home/campaigns/scheduler/tests/testSchedulerModel.coffee:177:4)
at Module._compile (module.js:402:26)
at Object.run (/usr/local/lib/node_modules/coffee-script/lib/coffee-script.js:57:25)
However, on line 12 of testSchedulerModel.coffee there is no reference to 'name'. Here is what line 12 looks like:
ObjectId = Schema.ObjectId
So how should I understand this error?
Thank you,
Igor

Sigh. Unfortunately, while you'd think testSchedulerModel.coffee:12 would mean "line 12 of testSchedulerModel.coffee, it actually means "line 12 of the JavaScript that testSchedulerModel.coffee is compiled to. The problem is that there's currently no way to trace errors back to the original CoffeeScript (at least not under Node).
So, you'll have to compile testSchedulerModel.coffee as JS and see what line 12 is there.
Better debugging tools for CoffeeScript are coming, but for now, it's probably best that you set up a Cakefile that compiles your code to JS before running it, to avoid such confusion.
By the way, there is an open issue regarding those .coffee filenames in the stack trace: issue 987.

Trevor: Kudos for the tip!
I solved my issue. It turns out that I cannot have objects inside of arrays when defining my schema in Mongoose. I was doing it like this:
AdUnitSchema = new mongoose.Schema
venue: [
{
id: ObjectId,
name: String
}
],
geotarget: [
{
id: ObjectId,
name: String
}
]
But in actuality, I had to create separate schemas, and reference them like this:
AdUnitSchema = new mongoose.Schema
venue:
[VenueSchema]
geotarget:
[GeotargetSchema]

Related

Stop huge error output from testing-library

I love testing-library, have used it a lot in a React project, and I'm trying to use it in an Angular project now - but I've always struggled with the enormous error output, including the HTML text of the render. Not only is this not usually helpful (I couldn't find an element, here's the HTML where it isn't); but it gets truncated, often before the interesting line if you're running in debug mode.
I simply added it as a library alongside the standard Angular Karma+Jasmine setup.
I'm sure you could say the components I'm testing are too large if the HTML output causes my console window to spool for ages, but I have a lot of integration tests in Protractor, and they are SO SLOW :(.
I would say the best solution would be to use the configure method and pass a custom function for getElementError which does what you want.
You can read about configuration here: https://testing-library.com/docs/dom-testing-library/api-configuration
An example of this might look like:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
You can then put this in any single test file or use Jest's setupFiles or setupFilesAfterEnv config options to have it run globally.
I am assuming you running jest with rtl in your project.
I personally wouldn't turn it off as it's there to help us, but everyone has a way so if you have your reasons, then fair enough.
1. If you want to disable errors for a specific test, you can mock the console.error.
it('disable error example', () => {
const errorObject = console.error; //store the state of the object
console.error = jest.fn(); // mock the object
// code
//assertion (expect)
console.error = errorObject; // assign it back so you can use it in the next test
});
2. If you want to silence it for all the test, you could use the jest --silent CLI option. Check the docs
The above might even disable the DOM printing that is done by rtl, I am not sure as I haven't tried this, but if you look at the docs I linked, it says
"Prevent tests from printing messages through the console."
Now you almost certainly have everything disabled except the DOM recommendations if the above doesn't work. On that case you might look into react-testing-library's source code and find out what is used for those print statements. Is it a console.log? is it a console.warn? When you got that, just mock it out like option 1 above.
UPDATE
After some digging, I found out that all testing-library DOM printing is built on prettyDOM();
While prettyDOM() can't be disabled you can limit the number of lines to 0, and that would just give you the error message and three dots ... below the message.
Here is an example printout, I messed around with:
TestingLibraryElementError: Unable to find an element with the text: Hello ther. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
...
All you need to do is to pass in an environment variable before executing your test suite, so for example with an npm script it would look like:
DEBUG_PRINT_LIMIT=0 npm run test
Here is the doc
UPDATE 2:
As per the OP's FR on github this can also be achieved without injecting in a global variable to limit the PrettyDOM line output (in case if it's used elsewhere). The getElementError config option need to be changed:
dom-testing-library/src/config.js
// called when getBy* queries fail. (message, container) => Error
getElementError(message, container) {
const error = new Error(
[message, prettyDOM(container)].filter(Boolean).join('\n\n'),
)
error.name = 'TestingLibraryElementError'
return error
},
The callstack can also be removed
You can change how the message is built by setting the DOM testing library message building function with config. In my Angular project I added this to test.js:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
This was answered here: https://github.com/testing-library/dom-testing-library/issues/773 by https://github.com/wyze.

ArangoDB "Spring Data Demo" Tutorial outdated?

Like the title says, is it possible the tutorial at https://www.arangodb.com/tutorials/spring-data/ is outdated? I'm having several problems, but don't know how to workaround the last one:
Part 2, "Save and read an entity"
I get an error: method getId() is undefined.
Workaround: I added a getter in class Character.
Also in "Save and read an entity"
final Character foundNed = repository.findOne(nedStark.getId());
The method findOne(Example) in the type QueryByExampleExecutor is not applicable for the arguments (String)
Workaround: I used find by example:
final Optional<Person> foundNed = repository.findOne(Example.of(nedStark));
Part 1, "Create a Configuration class"
public class DemoConfiguration extends AbstractArangoConfiguration {
Gives me an error:
"No constructor with 1 argument defined in class 'com.arangodb.springframework.repository.ArangoRepositoryFactoryBean'"
Workaround: ?
Can anyone point me in the right direction?
I found the demo project on github: https://github.com/arangodb/spring-data-demo
Number 1: They use a getter too.
Number 2: Was my fault, I did try ArangoRepository (of Character, Integer) but forgot that Id is a string.
Number 3: They don't seem use any Configuration (AbstractArangoConfiguration) class in the source at all although it is still mentioned in that tutorial. I think now the config and connection is handled by spring autoconfigure. Though I would like to know how the Arango driver is set, all I could find that may point further is ArangoOperations.
Anyway it works now, maybe this helps somebody else who is having the same problems.

sails.models.['CollectionName'] is not working in latest Sails Version

I am trying to access Model component via sails.models.['CollectionName'] as these CollectionName will be dynamically sent into this piece of functionality. But it is throwing undefined error.
/sails12.rc3/myapps/api/services/UserService.js:86
var findQuery = sails.models['User'].find({id: inputID
^
/sails12.rc3/myapps/api/services/UserService.js:86
var findQuery = sails.config.models['User'].find({id: inputID
^
/sails12.rc3/myapps/api/services/UserService.js:86
var findQuery = sails.config.models['user'].find({id: inputID
^
TypeError: Cannot read property 'find' of undefined
at Object.UserService.formNewData
(/sails12.rc3/myapps/api/services/UserService.js:86:52)
at Object.bound [as formNewData] (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
at /sails12.rc3/myapps/api/services/UserInfoService.js:330:37
at fn (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:638:34)
at Immediate._onImmediate (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:554:34)
at processImmediate [as _immediateCallback] (timers.js:358:17)
Please note that sails.config is working perfectly fine..
I am using SailsJS 12 rc 3. ( I mean the latest Version at this time ).
Can you please suggest me about the troubleshooting in this regard.
Update 1:
Hi Jason,
In all 3 cases, the same errror.
I could technically confirm that you are right on
http://sailsjs.org/documentation/reference/configuration/sails-config-models
Still, I am not sure, if there are any update requires in
http://sailsjs.org/documentation/anatomy/my-app/config/models-js
currently in config/models.js,
module.exports.models = {
connection: 'mongoDB',
migrate: 'alter'
}
Please suggest if I need to update any config values in this models.js file?
Update 2
https://github.com/balderdashy/sails/blob/master/lib/hooks/orm/build-orm.js
I could see the following values for these global values
sails.config.models { connection: 'mongoDB', migrate: 'alter' }
sails.config.globals { adapters: true, models: true, services: true }
sails.config.globals.models true
And hence mine is not working..Please suggest some options.
Update 3
Thanks Travis. sails.models['user'].find is working fine without no change in the SailsJS version. So, let me test some more time.
Ps: Not sure, why i am unable to add a comment directly below ( MAC / chrome browser) . So, for now, editing this question itself.
I think you're accessing it incorrectly.
Try: sails.config.models['User']
Try converting the model name to lowercase.
sails.models['CollectionName'] will not work, because within the models object, the collection names are all lowercase.
sails.model['collectionname'] should work.
I'm not sure why this is, but I think it will be something in the building of the ORM in waterline.
edit : I think this happens here

Moped::Errors::OperationFailure when creating an embedded object

I'm using mongoid 3.1.4 altogether with moped 1.5.1, mongodb 2.4.1, and ruby 1.9.3.
I have next models:
class Practice
include Mongoid::Document
embeds_many :distresses
end
class Distress
include Mongoid::Document
embedded_in :practice
end
When I do something like this it seems to be working:
practice = Practice.create
practice.distresses.create
But when I place safe: true in my config file and I do the same, then I get:
Moped::Errors::OperationFailure: The operation: #<Moped::Protocol::Command
#length=82
#request_id=22
#response_to=0
#op_code=2004
#flags=[]
#full_collection_name="collection.$cmd"
#skip=0
#limit=-1
#selector={:getlasterror=>1, :safe=>true}
#fields=nil>
And actually, I got the error when creating the distress in any way. This also throws the exception:
practice = Practice.create
distress = practice.distresses.build
distress.save
When I check with practice.distresses.count I can see that distresses where created successfully in the database, however I get the exception mentioned above.
Ok, after some days I was able to fix this problem.
In my Distress model I had a before_create callback that was trying to update a field on the Practice parent object. Somehow this makes Moped to create a wrong request that makes MongoDB to fail.
I changed before_create callback for after_create and everything is working now.
Hope this helps somebody else.

GetExportedValues<MyType> returns nothing, I can see the parts

I have a strange MEF problem, I tested this in a test project and it all seems to work pretty well but for some reason not working in the real project
This is the exporting code
public void RegisterComponents()
{
_registrationBuilder = new RegistrationBuilder();
_registrationBuilder
.ForTypesDerivedFrom(typeof(MyType))
.SetCreationPolicy(CreationPolicy.NonShared)
.Export();
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(typeof(MyType).Assembly, _registrationBuilder));
var directoryCatalog = new DirectoryCatalog(PathToMyTypeDerived, _registrationBuilder);
catalog.Catalogs.Add(directoryCatalog);
_compositionContainer = new CompositionContainer(catalog);
_compositionContainer.ComposeParts();
var exports = _compositionContainer.GetExportedValues<MyType>();
Console.WriteLine("{0} exports in AppDomain {1}", exports.Count(), AppDomain.CurrentDomain.FriendlyName);
}
exports count is 0 :( Any ideas why?
IN the log file I have many of this
System.ComponentModel.Composition Information: 6 : The ComposablePartDefinition 'SomeOthertype' was ignored because it contains no exports.
Though I would think this is ok because I wasn' interested in exporting 'someOtherType'
UPDATE: I found this link but after debuging over it I am not wiser but maybe I m not following up properly.
Thanks for any pointers
Cheers
I just had the same problem and this article helped me a lot.
It describes different reasons why a resolve can fail. One of the more important ones is that the dependency of a dependency of the type you want to resolve is not registered.
What helped me a lot was the the trace output that gets written to the Output window when you debug your application. It describes exactly the reasons why a type couldn't be resolved.
Even with this output. you might need to dig a little bit, because I only got one level deep.
Example:
I wanted to resolve type A and I got a message like this:
System.ComponentModel.Composition Warning: 1 : The ComposablePartDefinition 'Namespace.A' has been rejected. The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced multiple composition errors, with 1 root causes. The root causes are provided below. Review the CompositionException.Errors property for more detailed information.
1) No exports were found that match the constraint:
ContractName Namespace.IB
RequiredTypeIdentity Namespace.IB
Resulting in: Cannot set import 'Namespace.A..ctor (Parameter="b", ContractName="namespace.IB")' on part 'Namespace A'.
Element: Namespace.A..ctor (Parameter="b", ContractName="Namespace.IB") --> Namespace.A --> AssemblyCatalog (Assembly="assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=...")
But I clearly saw a part for Namespace.IB. So, in the debugger, I tried to resolve that one. And I got another trace output. This time it told me that my implementation of Namespace.IB couldn't be resolved because for one of its imports there was a missing export, so basically the same message as above, just with different types. And this time, I didn't find a part for that missing import. Now I knew, which type was the real problem and figure out, why no registration happened for it.