小编Nen*_*vic的帖子

MongooseError:查询已执行:Todo.updateOne({ _id: new ObjectId("612df063a8f

我将猫鼬更新到最新版本(6.0.2),现在我收到此错误并在.updateOne()执行时粉碎应用程序。但是数据库内部的对象更新。我的代码:

\n
async(req,res) => {\n    await Todo.updateOne(\n        {_id : req.params.id},\n        {\n            $set : {\n                status : "inactive"\n            }\n        },\n        (updateError) => {\n            // if updateError exist\n            if (updateError) {\n                // print error\n                printError(updateError);\n\n                // response the error\n                res.status(500).json({\n                    error : "There was a Server Side Error!"\n                });\n            } else {\n                // if error dose not exist\n                // print message\n                console.log("|===> \xef\xb8\x8f  Data Was Updated successfully! \xef\xb8\x8f <====|\\n");\n                // response success\n                res.json({\n                    message : "Todo Was Update successfully!"\n                });\n …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose mongodb node.js express

7
推荐指数
2
解决办法
7255
查看次数

无法加载配置“更漂亮”来扩展

我使用 Prettier 作为格式化程序,所以我配置了eslint-plugin-prettier. 我按照本指南做了所有事情,但是当我尝试运行 ng lint 时,出现此错误:

An unhandled exception occurred: Failed to load config "prettier" to extend from.
Referenced from: ...\node_modules\eslint-plugin-prettier\eslint-plugin-prettier.js
Run Code Online (Sandbox Code Playgroud)

这是我的.eslintrc.json

An unhandled exception occurred: Failed to load config "prettier" to extend from.
Referenced from: ...\node_modules\eslint-plugin-prettier\eslint-plugin-prettier.js
Run Code Online (Sandbox Code Playgroud)

从我的package.json

{
  "root": true,
  "ignorePatterns": ["projects/**/*"],
  "overrides": [
    {
      "files": ["*.ts"],
      "parserOptions": {
        "project": ["tsconfig.json", "e2e/tsconfig.json"],
        "createDefaultProgram": true
      },
      "extends": [
        "plugin:@angular-eslint/recommended",
        "plugin:@angular-eslint/template/process-inline-templates",
        "plugin:prettier/recommended"
      ],
      "rules": {
        "@angular-eslint/directive-selector": [
          "error",
          {
            "type": "attribute",
            "prefix": …
Run Code Online (Sandbox Code Playgroud)

javascript eslint angular prettier prettier-eslint

7
推荐指数
1
解决办法
1万
查看次数

Serverless Express 关闭 mongodb 连接

我在aws上使用无服务器,以nodejs和mongodb atlas作为数据库

目前我使用的是试用版,最多允许 500 个连接。

似乎我的代码在进程结束时没有断开数据库连接

我正在使用express来管理它

首先,我没有关闭连接,认为一旦进程结束,连接就会自动关闭,但我没有打开很多连接。

然后我添加了一个中间件来在发送响应后关闭我的连接,它不起作用,我认为无服务器在响应发送后就会停止进程。

例如,并非在每条路线上我都会关闭 mongo 连接

router.get('/website/:id/page', async (req, res, next) => {
  try {
    const pages = await pageDataProvider.findByWebsite(req.params.id);
    await mongodbDataProvider.close();
    res.json(pages);
  } catch (error) {
    next(error)
  }
})
Run Code Online (Sandbox Code Playgroud)

这就是我处理与 mongo 的连接的方式

const MongoClient = require('mongodb').MongoClient
const config = require('../config')

const MONGODB_URI = config.stage === 'test' ?
  global.__MONGO_URI__ :
  `mongodb+srv://${config.mongodb.username}:${config.mongodb.password}@${config.mongodb.host}/admin?retryWrites=true&w=majority`;
const client = new MongoClient(MONGODB_URI);

let cachedDb = null;

module.exports.connect = async () => {

  if (cachedDb) return cachedDb;

  await client.connect();

  const dbName …
Run Code Online (Sandbox Code Playgroud)

javascript mongodb node.js express serverless

7
推荐指数
1
解决办法
826
查看次数

如何使用 Mongoose 创建时间序列集合

MongoDB v5.0 引入了一种新的集合类型,该类型针对存储和处理时间序列数据进行了优化 -时间序列集合。我们如何使用 Mongoose 创建时间序列集合?

time-series mongoose mongodb

7
推荐指数
1
解决办法
6525
查看次数

在 Mat-Select 中滚动到 Mat-0ptions 末尾时触发事件:Angular 6

我最近开始修改一个基于 Angular 6 的项目,但遇到了一些问题。因此,我有(假设)4 个 Mat-Select 字段,分别用于语言、货币、国家和组织。

最初所有下拉菜单都有 10 个默认值,我通过调用 API 来获取。我的要求是,一旦用户滚动到选择下拉菜单时打开的 Mat-Options 框的末尾,就进行另一个 API 调用。

我已经提到了这个问题,它工作正常,但有一些问题,我注意到了。该答案涵盖了一个领域的解决方案。如果我们使用多个字段,我们是否必须重复代码?

这是HTML

            <mat-select [disabled]="isDisabled" [(ngModel)]="model.currency" name="currency" (selectionChange)="OnChange('currency',$event.value)" #currency>   
              <mat-option [value]="getCurrency.currencyCode" *ngFor="let getCurrency of fetchCurrency | 
                    filternew:searchCurrencyvaluedrop">{{ getCurrency.currencyDescription }}
              </mat-option>
            </mat-select>

          <mat-select [disabled]="isDisabled" [(ngModel)]="model.language" name="language"
                (selectionChange)="OnChange('language', $event.value)" #language>                      
            <mat-option [value]="getLanguage.languageDescription" *ngFor="let getLanguage of fetchLanguage | 
                  filternew:searchLanguagevaluedrop">{{ getLanguage.languageDescription }}</mat-option>
          </mat-select>
Run Code Online (Sandbox Code Playgroud)

为简单起见,我只添加了两个字段。以下是 .ts 中的代码:


  viewIndex = 0;
  windowSize = 10;
  private readonly PIXEL_TOLERANCE = 3.0;

  ngAfterViewInit() {
    this.selectElemCu.openedChange.subscribe((event) =>
      this.registerPanelScrollEventCurrency(event)
    );
    this.selectElem.openedChange.subscribe((event) => …
Run Code Online (Sandbox Code Playgroud)

javascript typescript angular-material angular angular6

6
推荐指数
1
解决办法
134
查看次数

从 JSON 字符串中拆分有效负载

我通过 WebSocket 收到这些巨大的字符串:

[
  "BTC-31DEC21-100000-P",
  "{\"data\":{\"bids\":{\"0.01\":{\"price\":0.01,\"volume\":66.2,\"exchange\":\"DER\"},\"5.0E-4\":{\"price\":5.0E-4,\"volume\":1.1,\"exchange\":\"DER\"},\"0.637\":{\"price\":0.637,\"volume\":8.4,\"exchange\":\"DER\"}},\"asks\":{\"0.664\":{\"price\":0.664,\"volume\":8.4,\"exchange\":\"DER\"}}},\"isMasterFrame\":true}"
]
Run Code Online (Sandbox Code Playgroud)

或者

[
  "BTC-31DEC21-36000-C",
  "{\"data\":[{\"price\":0.422,\"volume\":8.4,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
]
Run Code Online (Sandbox Code Playgroud)

或者

[
  "BTC-31DEC21-60000-P",
  "{\"data\":[{\"price\":0.105,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1055,\"volume\":28.7,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.106,\"volume\":7.6,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1065,\"volume\":43.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
]
Run Code Online (Sandbox Code Playgroud)

我想检查一下isMasterFrame

let payload = JSON.parse(messageString[1]);

if (payload.hasOwnProperty("isMasterFrame")) {
 for (let i = 0; i < payload.pairs.length; i++) {
   let currentPair = payload.data[i]
      currentPair = currentPair.replace(/\0/g, ''); //Remove null chars
       if (currentPair.toUpperCase() != 'KILL') {
           props.onAddAvailablePair(currentPair);
        }
       }
      } else {
             // print some output with payload which holds "isMasterFrame":false
     }
Run Code Online (Sandbox Code Playgroud)

当我运行代码时出现错误:

TypeError: Cannot read properties of undefined (reading 'length')
Run Code Online (Sandbox Code Playgroud)

来自一对内部对的数据:{\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}应该被拆分并一一插入到循环中 …

javascript json

6
推荐指数
1
解决办法
1147
查看次数

Mongoose 索引 html 文本?

我有一个带有 html 字段的文档。html字段存储真实的html。

schema: {
  html: String
}
Run Code Online (Sandbox Code Playgroud)
doc: {
  "html" : "<p>I am html<p>"
}
Run Code Online (Sandbox Code Playgroud)

我想索引 html 字段,当我搜索“我是 html”时,它应该返回该文档。

有没有什么方法可以仅使用该 html 标记内的文本来搜索该文档。

html javascript mongoose node.js typescript

6
推荐指数
1
解决办法
91
查看次数

如何在 Stripe 结帐会话中访问项目元数据

当我创建结帐会话时,我正在使用price_dataproduct_data属性动态创建价格。对于每个项目,我都将元数据放入属性中product_data.metadata

付款成功完成后,我获取会话数据以便向客户显示付款成功页面。但由于某种原因,项目的元数据为空。当我在仪表板中检查项目时,项目的元数据存在,但当我使用 API 获取它时,它们是空的。

我尝试使用扩展属性获取整个会话数据line_items

const session = await stripe.checkout.sessions.retrieve(session_id, { expand: ['line_items'] });
Run Code Online (Sandbox Code Playgroud)

我还尝试直接获取项目:

const line_items = await stripe.checkout.sessions.listLineItems(session_id);
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,每个项目的元数据都是空的。

javascript node.js express stripe-payments

6
推荐指数
1
解决办法
1624
查看次数

Angular Tap 已弃用

我的角度应用程序中有以下 http 拦截器:

    import { Observable } from 'rxjs';
    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpResponse } from '@angular/common/http';
    import { HttpRequest } from '@angular/common/http';
    import { HttpHandler } from '@angular/common/http';
    import { HttpEvent } from '@angular/common/http';
    import { tap } from 'rxjs/operators';
    import { SpinnerService } from '../sharedServices/spinner.service';
    
    @Injectable()
    export class CustomHttpInterceptor implements HttpInterceptor {
    
        constructor(private spinnerService: SpinnerService) { }
    
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    
            this.spinnerService.show();
            
            return next.handle(req)
                 .pipe(tap((event: HttpEvent<any>) => {
                        if (event instanceof …
Run Code Online (Sandbox Code Playgroud)

javascript rxjs typescript angular-material angular

6
推荐指数
1
解决办法
3363
查看次数

导入时baseUrl和node_modules冲突

我有一个 TS 项目,配置如下:

tsconfig.json(部分)

{
  "compilerOptions": {
    "module": "commonjs",
    "baseUrl": "src",
    "esModuleInterop": true,
  },
  "include": [
    "src"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我对 NPM 包有依赖stripe

{
  // ...
  "dependencies": {
    "stripe": "^8.45.0",
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我有以下文件:

src/routes/payments/index.ts
src/stripe/index.ts
Run Code Online (Sandbox Code Playgroud)

我在导入时遇到一些问题src/routes/payments/index.ts。我想导入stripe库,而不是我自己的代码。

这有效:

// Uses me the 'Stripe' constructor which is the default export from the package
const stripe = require('stripe')('KEY');
Run Code Online (Sandbox Code Playgroud)

这不起作用:

import Stripe from 'stripe';
const stripe = new Stripe('KEY');
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Module '"PROJECT/src/stripe/index"' has no default export.
Run Code Online (Sandbox Code Playgroud)

如何消除歧义并告诉 TS 我想 …

javascript node.js npm stripe-payments typescript

5
推荐指数
1
解决办法
773
查看次数