使用 MikroORM 并收到此错误:
ValidationError: Using global EntityManager instance methods for context specific actions is disallowed.
If you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead
Run Code Online (Sandbox Code Playgroud)
其对应的代码如下:
import { MikroORM } from "@mikro-orm/core";
import { __prod__ } from "./constants";
import { Post } from "./entities/Post";
import mikroConfig from "./mikro-orm.config";
const main = async () => {
const orm = await MikroORM.init(mikroConfig);
const post = orm.em.create(Post, {
title: "my first post",
});
await orm.em.persistAndFlush(post); …Run Code Online (Sandbox Code Playgroud) 我有一个生产项目要开发。这是一个电子商务网站。我目前的堆栈:
现在我必须为这个项目选择一个 ORM。我想我有两个选择:
缺乏维护和功能但稳定的 ORM 或具有良好维护和新功能但未经实战测试的 ORM。哪个选项更好?或者也许有一些替代方案?
我想为 NestJS 控制器实现 JSON 请求/响应正文的自动序列化/反序列化,准确地说,自动将snake_case请求正文 JSON 键转换为camelCase在我的控制器处理程序处接收,反之亦然。
我发现使用class-transformer's @Expose({ name: 'selling_price' }),如下例所示(我正在使用 MikroORM):
// recipe.entity.ts
@Entity()
export class Recipe extends BaseEntity {
@Property()
name: string;
@Expose({ name: 'selling_price' })
@Property()
sellingPrice: number;
}
Run Code Online (Sandbox Code Playgroud)
// recipe.controller.ts
@Controller('recipes')
export class RecipeController {
constructor(private readonly service: RecipeService) {}
@Post()
async createOne(@Body() data: Recipe): Promise<Recipe> {
console.log(data);
return this.service.createOne(data);
}
}
Run Code Online (Sandbox Code Playgroud)
// example request body
{
"name": "Recipe 1",
"selling_price": 50000
}
Run Code Online (Sandbox Code Playgroud)
// log on the RecipeController.createOne …Run Code Online (Sandbox Code Playgroud) 所以我正在使用 type-graph 和 mikro-orm 创建一个 graphQL 服务器,一切都很好,直到我收到此错误,显示 => Error: Cannot find module 'src/entities/Post' 并且该模块存在,如您在这张图片中看到的那样: 文件夹结构
这就是终端中错误的样子:终端中的错误
顺便说一句,我正在使用名为 watch: "tsc -w" 的脚本将 typescript 转换为 javascript。
这是我的 postResolver 的代码示例:
import { Post } from './src/entities/Post';
import { MyContext } from 'src/types';
import {Ctx, Query, Resolver} from 'type-graphql';
@Resolver()
export class postResolver {
@Query(()=> [Post])
posts(@Ctx() {em}: MyContext) : Promise<Post[]>{
return em.find(Post, {})
}
}Run Code Online (Sandbox Code Playgroud)
我正在尝试按照这个React GraphQL TypeScript 教程编写代码
该项目使用 MikroOrm 与 PostgreSQL 数据库进行通信。我在我的 Ubuntu 18.04 上安装了 PostgreSQL(12.4),创建了一个“postgres”用户,我可以登录该用户并正常运行psql。但是,当我开始使用(视频时间戳)之mikro-orm类的命令时,出现以下错误:npx mikro-orm migration:create
error: password authentication failed for user "postgres"
at Parser.parseErrorMessage (/home/<username>/newstack/node_modules/pg-protocol/src/parser.ts:357:11)
at Parser.handlePacket (/home/<username>/newstack/node_modules/pg-protocol/src/parser.ts:186:21)
at Parser.parse (/home/<username>/newstack/node_modules/pg-protocol/src/parser.ts:101:30)
at Socket.<anonymous> (/home/<username>/newstack/node_modules/pg-protocol/src/index.ts:7:48)
at Socket.emit (events.js:315:20)
at Socket.EventEmitter.emit (domain.js:483:12)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)
at Socket.Readable.push (_stream_readable.js:212:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
length: 104,
severity: 'FATAL',
code: '28P01',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined, …Run Code Online (Sandbox Code Playgroud) 在以下场景中,整个SalesOrder实体被传递到销售订单实体的服务器项目集合中,可以包含新项目、删除项目和更新项目。只是坚持SalesOrder不起作用(不会删除或更新),这就是我让它工作的方式。有没有更好的办法?或者我错过了什么?
async save(@Body() item: SalesOrder) {
let result: SalesOrder;
result = await em.getRepository<SalesOrder>(SalesOrder).findOne(item.id);
item.items.forEach(k => k.salesOrder = item.id)
await this.em.getRepository(SalesOrderItem).nativeDelete({ salesOrder: item.id })
for (const [i, it] of item.items.entries()) {
const x = em.getRepository(SalesOrderItem).create({ ...it })
await em.persistAndFlush(x)
}
wrap(result).assign({ ...item, items: null }, {})
await em.getRepository(SalesOrder).persistAndFlush(result);
await em.flush()
}
Run Code Online (Sandbox Code Playgroud)
@Entity()
export class SalesOrder extends BaseEntity {
@PrimaryKey( )
id: number;
@OneToMany(i => SalesOrderItem, t => t.salesOrder, { eager: true, cascade: [Cascade.ALL] })
items = new …Run Code Online (Sandbox Code Playgroud) 这就是我当前正在尝试模拟的 SQL。
SELECT * FROM direct_messages AS T
INNER JOIN (SELECT sender_id, receiver_id, MAX(sent_at) AS sent_at FROM direct_messages WHERE (sender_id = '2' OR sender_id = '3') AND (receiver_id = '3' OR receiver_id = '2') GROUP BY sender_id, receiver_id) A
ON A.sender_id = T.sender_id AND A.sent_at = T.sent_at;
Run Code Online (Sandbox Code Playgroud)
这是表的实体
@ObjectType()
@Entity()
export class DirectMessages {
@Field(() => ID)
@PrimaryKey()
id!: number;
@Field(() => String)
@Property()
senderID!: string;
@Field(() => String)
@Property()
receiverID!: string;
@Field(() => String)
@Property()
message!: string;
@Field(() => …Run Code Online (Sandbox Code Playgroud) 我正在尝试弄清楚如何定义其他可选属性。
import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';
@Entity()
export abstract class BaseEntity {
[OptionalProps]?: 'createdAt';
@PrimaryKey()
id: number;
@Property()
createdAt: Date = new Date();
}
@Entity()
export class EntityA extends BaseEntity {
[OptionalProps]?: 'isAnotherProperty'; // This is the bit I cannot figure out
@Property()
isAnotherProperty: boolean = false;
}
Run Code Online (Sandbox Code Playgroud)
使用上面的 TypeScript 会抛出错误:
Property '[OptionalProps]' in type 'EntityA' is not assignable to the same property in base type 'BaseEntity'.
Run Code Online (Sandbox Code Playgroud)
基本上 myBaseEntity有可选属性,就像EntityA. 我可以删除[OptionalProps]?:from …
我正在尝试一次创建和更新多个实体(模型)。我通过使用insertGraphAPI在反对 ORM 中做到了这一点,如果它没有 id,它实际上插入实体,如果它有 id 则更新。
MikroORM 中是否有类似的 API?
目前我正在这样做:
app.put('/articles', async (req, res) => {
const save = req.body.articles.map(async (dto) => {
const article = Object.assign(new Article(), dto)
await req.em.persistAndFlush(article)
})
await Promise.all(save)
res.send({ ok: true })
})
Run Code Online (Sandbox Code Playgroud)
但它会生成多个交易,我想在单个交易中完成所有事情。
我正在一步步按照教程进行操作,当我到达 run 部分时npx mikro-orm migration:create,出现此错误
TypeError [ERR_INVALID_ARG_TYPE]: The "key" argument must be of type string or an instance of Buffer, TypedArray, DataView, or KeyObject. Received null
at prepareSecretKey (internal/crypto/keys.js:322:11)
at new Hmac (internal/crypto/hash.js:113:9)
at Object.createHmac (crypto.js:147:10)
at createHMAC (C:\lireddit-server\node_modules\pg\lib\sasl.js:133:17)
at Hi (C:\lireddit-server\node_modules\pg\lib\sasl.js:137:13)
at Object.continueSession (C:\lireddit-server\node_modules\pg\lib\sasl.js:32:24)
at Client._handleAuthSASLContinue (C:\lireddit-server\node_modules\pg\lib\client.js:248:10)
at Connection.emit (events.js:314:20)
at Connection.EventEmitter.emit (domain.js:483:12)
at C:\lireddit-server\node_modules\pg\lib\connection.js:109:12
at Parser.parse (C:\lireddit-server\node_modules\pg-protocol\src\parser.ts:102:9)
at Socket.<anonymous> (C:\lireddit-server\node_modules\pg-protocol\src\index.ts:7:48)
at Socket.emit (events.js:314:20)
at Socket.EventEmitter.emit (domain.js:483:12)
at addChunk (_stream_readable.js:298:12)
at readableAddChunk (_stream_readable.js:273:9)```
I can't find any …Run Code Online (Sandbox Code Playgroud) mikro-orm ×10
node.js ×4
typescript ×4
javascript ×3
orm ×3
postgresql ×3
graphql ×1
nestjs ×1
sql ×1
typegraphql ×1
typeorm ×1
ubuntu-18.04 ×1