【问题标题】:Am I missing a package? Property 'findOne' does not exist on type 'Schema<Document<any, {}>, Model<any, any>, undefined>'我错过了一个包裹吗?类型 'Schema<Document<any, {}>, Model<any, any>, undefined>' 上不存在属性 'findOne'
【发布时间】:2022-03-05 11:19:52
【问题描述】:

我已获得公司的网站进行维护,但我遇到了错误(在类型 'Schema, Model 上不存在属性 'findOne' , 未定义>')

此站点当前正在运行,我从 GitHub 中提取了代码。我想弄清楚我是否缺少包裹或其他东西。

这是我的 package.json:

    {
  "name": "zenexint.com",
  "version": "4.0.0",
  "private": true,
  "main": "bin/build/server.bundle.js",
  "description": "ZenexInt.com",
  "scripts": {
    "watch": "webpack -d -w --env.development",
    "build": "webpack -p --env.production"
  },
 
  "devDependencies": {
    "@babel/core": "^7.14.0",
    "@types/mongoose": "5.10.5",
    "@types/node": "^6.9.2",
    "@types/react": "^16.8.4",
    "@types/react-dom": "^16.8.4",
    "@types/react-router": "^5.1.3",
    "source-map-loader": "^0.2.4",
    "ts-loader": "^6.2.1",
    "typescript": "^3.7.4",
    "webpack": "^4.46.0",
    "webpack-cli": "^4.6.0"
  },
  "dependencies": {
    "antd": "^4.0.0",
    "axios": "^0.21.1",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "client-sessions": "^0.8.0",
    "cookie-parser": "^1.4.4",
    "express": "^4.17.1",
    "is-plain-object": "^2.0.4",
    "jsonwebtoken": "^8.5.1",
    "kind-of": "^6.0.3",
    "mongodb": "^3.4.0",
    "mongoose": "^5.12.6",
    "nodemailer": "^6.2.1",
    "nodemailer-smtp-transport": "^2.7.4",
    "npm": "^7.11.1",
    "pug": "^3.0.2",
    "react": "^16.8.4",
    "react-dom": "^16.8.4",
    "react-google-recaptcha": "^1.0.5",
    "react-magnifier": "^3.0.4",
    "react-redux": "^7.1.3",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "redux": "^4.0.4",
    "redux-thunk": "^2.3.0"
  }
}

这是产生错误的代码:

import express from "express";

import { set_catalog, set_meta, } from "../redux/actions";
import { ZenexProduct as Product } from '../models/mongoose/models';
import { MetaProducts } from "../meta";
import { mapItems } from "./utils";
import { ZenexItem } from "../models/mongoose/schemas";

import Catalog from "../models/Catalog";

var r = express.Router();

r.use((req, res, next) => {

    let catalog = Catalog();

    if (req.query.limit) { catalog.limit = Number(req.query.limit); }
    if (req.query.skip) { catalog.skip = Number(req.query.skip); }
    if (req.query.sort) { catalog.sort = req.query.sort; }

    res.locals.store.dispatch(set_catalog(catalog));
    res.locals.store.dispatch(set_meta(MetaProducts));

    next();

});

r.use('/category/:Category/:Subcategory', async (req, res, next) => {

    const { Category, Subcategory } = req.params;
    let { catalog, meta } = res.locals.store.getState();

    let q = { $and: [{ Category: { $regex: Category, $options: "i" } }, { Subcategory: { $regex: Subcategory, $options: "i" } }] };
    catalog.count = await Product.find(q).countDocuments().exec()
    catalog.items = (await Product.find(q).sort(catalog.sorts[catalog.sort]).skip(catalog.skip).limit(catalog.limit).exec()).map(d => d._doc);
    catalog.category = Category;
    catalog.subcategory = Subcategory;
    meta.title = 'Private Label ' + Subcategory + ': Zenex International';
    meta.description = 'We manufacture and can private label ' + Subcategory + ' and other quality products for your business today.';
    res.locals.store.dispatch(set_catalog(catalog));
    res.locals.store.dispatch(set_meta(meta));

    next();

});

r.use('/category/:Category', async (req, res, next) => {

    const { Category } = req.params;
    let { catalog, meta } = res.locals.store.getState();

    //if(formalize(Category) !== Category) { res.redirect("/category/" + formalize(Category)); }

    if (catalog.items.length === 0) {
        let q = { Category: { $regex: Category, $options: "i" } };
        catalog.count = await Product.find(q).countDocuments().exec();
        catalog.items = (await Product.find(q).sort(catalog.sorts[catalog.sort]).skip(catalog.skip).limit(catalog.limit).exec()).map(d => d._doc);
        catalog.category = Category;
        meta.title = 'Private Label ' + Category + ': Zenex International';
        meta.description = 'We manufacture and can private label ' + Category + ' and other quality  products for your business today.';
        res.locals.store.dispatch(set_catalog(catalog));
        res.locals.store.dispatch(set_meta(meta));
    }

    next();

});

r.use('/family/:Family', async (req, res, next) => {

    const { Family } = req.params;
    let { catalog, meta } = res.locals.store.getState();

    if (catalog.items.length === 0) {
        var query = { Family: Family.substring(0, Family.length - 1).toLowerCase() };
        catalog.count = await Product.find(query).countDocuments().exec();
        catalog.items = (await Product.find(query).sort(catalog.sorts[catalog.sort]).skip(catalog.skip).limit(catalog.limit).exec()).map(d => d._doc);
        meta.title = 'Private Label ' + Family + ': Zenex International';
        meta.description = 'Wholesale Distribution and Private Label ' + Family + 's: Zenex International';
        catalog.items = catalog.items;
        catalog.family = Family;
        res.locals.store.dispatch(set_catalog(catalog));
        res.locals.store.dispatch(set_meta(meta));
    }

    next();

});

r.use('/nameSearch/:text', async (req, res, next) => {

    const { text } = req.params;

    let { catalog, meta } = res.locals.store.getState();

    if (catalog.items.length === 0) {

        let query = ["ProductID", "Name", "Title", "Keywords", "Subcategory", "Category", "Description"].reduce((q, field) => {
            q.$or.push({ [field]: { "$regex": text, "$options": "i" } });
            q.$or.push({ $and: text.split(' ').map(t => ({ [field]: { "$regex": t, "$options": "i" } })) });
            return q;
        }, { $or: [] });

        catalog.search = text;
        catalog.count = await Product.find(query).countDocuments().exec();

        if (catalog.count > 0) {
            catalog.items = (await Product.find(query).sort(catalog.sorts[catalog.sort]).limit(catalog.limit).skip(catalog.skip).exec()).map(d => d && d._doc);
            if (catalog.items.length === 1) { catalog.item = catalog.items[0]; }
            meta.title = "Professional Grade " + catalog.items[0].Category + " at Superior Value";
            meta.description = "We manufacturing and distribute " + catalog.items[0].Category + " and other high quality products for your business";
            res.locals.store.dispatch(set_catalog(catalog));
            res.locals.store.dispatch(set_meta(meta));
        }

    }

    next();

});

r.use('/:ProductID', async (req, res, next) => {

    const { ProductID } = req.params;
    let { catalog, meta } = res.locals.store.getState();

    if (catalog.items.length === 0) {
        catalog.count = await Product.find({ ProductID }).countDocuments().exec();
        catalog.item = (await Product.findOne({ ProductID }).exec());
        if (catalog.item) {
            catalog.item = catalog.item._doc;
            meta.title = `Private Label "${catalog.item.Name}: ${catalog.item.Title}", Zenex Intl.`;
            meta.description = `We private label "${catalog.item.Name}" ${catalog.item.Title}, and other ${catalog.item.Type}'s for your business today.`;
            catalog.category = catalog.item.Category;
            catalog.subcategory = catalog.item.Subcategory;
            catalog.family = catalog.item.Family;
            catalog.items = [catalog.item];
            res.locals.store.dispatch(set_catalog(catalog));
            res.locals.store.dispatch(set_meta(meta));
        }
    }

    next();

});

r.use("/", async (req, res, next) => {

    let { catalog } = res.locals.store.getState();

    if (catalog.items.length === 0) {
        catalog.count = await Product.find({}).countDocuments();
        catalog.items = (await Product.find({}).sort(catalog.sorts[catalog.sort]).skip(catalog.skip).limit(catalog.limit).exec()).map(d => d._doc);
    }

    catalog.items = catalog.items.map(mapItems);

    catalog.items.map(async (i, index) => {

        if (i.Hardware) {
            let hardware;
            try { hardware = await ZenexItem.findOne({ ProductID: i.Hardware }).exex(); }
            catch (error) { console.log(error); }
        }

        return i;

    });

    if (catalog.items.length === 1) {
        catalog.item = catalog.items[0];
    }

    res.locals.store.dispatch(set_catalog(catalog));

    next();

});

export default r;

我是不是遗漏了一些东西,还是我需要找到更大的问题?

【问题讨论】:

    标签: typescript mongoose webpack


    【解决方案1】:

    尝试将findOne 替换为find

    【讨论】:

    • 我在运行脚本之前安装了 npm (webpack --watch --mode=development)
    • 您可以尝试将findOne 替换为find 吗?
    • 这有助于解决这些问题,但我现在得到:属性 '_doc' 不存在于类型 'Document'
    • 你在调用什么端点?这意味着某些文档在数据库中没有_doc 字段。
    • 此部分正在访问一个 MongoDB 并且目录定义为:export default (obj?) => ({ categories: [], subcategories: [], items: [], item: null, category : null, subcategory: null, family: null, count: 0, limit: 10, skip: 0, search: "", content: null, page: 1, sort: "Popularity", sorts: { "Popularity": { “优先级”:-1 },“零件编号”:{“ProductID”:1 },“名称”:{“名称”:1 }, }, ...(obj || {}), });
    【解决方案2】:

    我遇到了同样的问题

    问题是你必须从模型扩展。

    要被允许在带有 typescript 的猫鼬中使用 findOne 方法,您必须先执行一些步骤:

    1. 创建界面
    2. 创建另一个从 Model 扩展的接口,并且必须是通用的
    3. 将这些接口实现到您的架构和模型中

    Here in mongoose documentation is very well explained,就我而言,我有

    interface IUser2 {
      name: string;
      username: string;
      password: string;
    }
    
    interface UserModel extends IUser2 {
      findUserByCredentials(): any;
    }
    

    它必须是

    interface IUser2 {
      name: string;
      username: string;
      password: string;
    }
    
                                   // look here
    // Extending from Model will allow you to use findOne method
    interface UserModel extends Model<IUser2> {
      findUserByCredentials(): any;
    }
    

    您的最终代码应如下所示

    import { Model, Schema, model } from 'mongoose';
    
    interface IUser {
      name: string;
    }
    
    interface UserModel extends Model<IUser> {
      myStaticMethod(): number;
    }
    
    const schema = new Schema<IUser, UserModel>({ name: String });
    schema.static('myStaticMethod', function myStaticMethod() {
      return 42;
    });
    
    const User = model<IUser, UserModel>('User', schema);
    
    const answer: number = User.myStaticMethod(); // 42
    

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 2023-04-03
      • 2022-12-17
      • 2018-08-02
      • 1970-01-01
      • 2021-05-09
      • 2021-02-08
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多