question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

`find` stripping off where options in node.js shell

See original GitHub issue

Issue type:

[x] question [ ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [x] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[ ] latest [ ] @next [x] ^0.2.20

Steps to reproduce or a small repository showing the problem:

Given the shell.js file below, a database (defined by databaseUrl) and a simple model (e.g. Person) run the following:

node shell
> db.persons.findOne(123)
Promise { <pending> }
> query: SELECT "Person"."id" AS "Person_id", "Person"."name" AS "Person_name" FROM "main_person" "Person" WHERE "Person"."id" IN ($1) LIMIT 1 -- PARAMETERS: [123]

> db.persons.find({ id: 123 })
Promise { <pending> }
> query: SELECT "Person"."id" AS "Person_id", "Person"."name" AS "Person_name" FROM "main_person" "Person"

Look at the logged queries. Notice that the first findOne example works properly, but in the second case Typeorm is stripping out any find arguments (in this case { id: 123 }).

Also note that the query function also succeeds for some reason (e.g. > query(123)).

// File: shell.js

// begin model Person.ts
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var typeorm_1 = require("typeorm");
var Person = /** @class */ (function () {
    function Person() {
    }
    __decorate([
        typeorm_1.PrimaryColumn('bigint'),
        __metadata("design:type", String)
    ], Person.prototype, "id", void 0);
    __decorate([
        typeorm_1.Column({ length: 50 }),
        __metadata("design:type", String)
    ], Person.prototype, "name", void 0);
    Person = __decorate([
        typeorm_1.Entity('person')
    ], Person);
    return Person;
}());
// end Person.ts

// begin shell
const repl = require('repl');
const { createConnection } = require('typeorm');

const m = {
    Person
};

const databaseUrl = '';

const connect = () => createConnection({
    type: 'postgres',
    url: databaseUrl,
    entities: Object.values(m),
    synchronize: false,
    logging: true,
    extra: {
      ssl: false,
    },
});

const shell = repl.start('> ');
connect().then(db => {
    db.persons = db.getRepository(m.Person);
    shell.context.query = (id) => db.persons.find({ id });
    shell.context.db = db;
    shell.context.m = m;
});

I have no idea why this isn’t working… any help would be much appreciated!

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:4
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

7reactions
kadenbarlowcommented, May 25, 2020
  • node@12.9.1
  • sqlite@4.2.0
  • typeorm@0.2.24

Hopes this helps someone in the future. I was having this same issue. Tracked it down to these lines in EntityManager.ts.

if (idOrOptionsOrConditions instanceof Object && !FindOptionsUtils.isFindOneOptions(idOrOptionsOrConditions))
            options = idOrOptionsOrConditions as ObjectLiteral;

I’m very new to javascript/typescript so I’m not sure why this was happening but idOrOptionsOrConditions instanceof Object was returning false here in the repl. This wasn’t happening when running the server.

I fixed it by setting useGlobal: true in my repl options

  const replServer = repl.start({
    prompt: 'app > ',
    useColors: true,
    ignoreUndefined: true,
    useGlobal: true,
  })
1reaction
mizozobucommented, May 4, 2020

Not sure why it is not working for you. I’m guessing, but could it be because of the pending promise? Then, consider using --experimental-repl-await.

I’ll just post what is working for me since this issue is the only thing I could find about Typeorm repl.


package.json

{
  ...
  "scripts": {
    ...
    "repl": "node -r ts-node/register --experimental-repl-await repl.ts"
  }
}

src/chat/chat.entity.ts

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
} from 'typeorm';

@Entity()
export class Chat {
  @PrimaryGeneratedColumn()
  readonly id: number;

  @Column()
  text: string;
}

repl.ts

import 'dotenv/config';
import { createConnection } from 'typeorm';
import { start } from 'repl';
import { Chat } from './src/chat/chat.entity';

/**
 * Rails like console for typeorm.
 * Type ".editor" to enter multi-line mode and "ctrl + D" to exit
 */
(async (): Promise<void> => {
  const connection = await createConnection({
    type: process.env.DB_TYPE,
    host: process.env.DATABASE_USER,
    port: Number(process.env.DB_PORT),
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    entities: [`${__dirname}/src/**/*.entity{.ts,.js}`],
    synchronize: true,
  });

  const chatRepository = connection.getRepository(Chat);

  const replServer = start({
    prompt: `${process.env.DB_NAME} > `,
    ignoreUndefined: true,
  });

  replServer.context.chatRepository = chatRepository;
})();

$ node -r ts-node/register --experimental-repl-await repl.ts
dbname > chat = await chatRepository.findOne({ id: 1 })
Chat {
  id: '1',
  text: 'asdf'
}
dbname > chat = await chatRepository.findOne({ id: 1 })
Chat {
  id: '1',
  text: 'asdf'
}

I’m on

  • node@12.14.0
  • mysql2@2.1.0
  • typeorm@0.2.24

Hope this helps.

Read more comments on GitHub >

github_iconTop Results From Across the Web

node process.argv is stripping caret (^) - Stack Overflow
I am trying to pass the caret character as an argument into node but process.argv is stripping off ...
Read more >
Node.js v19.3.0 Documentation
Indicates the failure of an assertion. All errors thrown by the node:assert module will be instances of the AssertionError class. new assert.AssertionError( ...
Read more >
Debug Node.js Apps using Visual Studio Code
The Visual Studio Code editor includes Node.js debugging support. Set breakpoints, step-in, inspect variables and more.
Read more >
Set up NodeJS on native Windows - Microsoft Learn
A guide to help you get your Node.js development environment set up directly on Windows.
Read more >
Why the Hell Would I Use Node.js? A Case-by-case Tutorial
On the server side, a simple Express.js application implements: A GET / request handler which serves the webpage containing a message board and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found