【问题标题】:mongoose: .find() is not a function猫鼬:.find() 不是函数
【发布时间】:2019-01-18 14:15:43
【问题描述】:

Stackoverflow 上现有的帖子都没有解决我的问题。我在路由器中有以下内容:

const express = require("express");
const mongoose = require("mongoose");
const User = require("./users/models");
const app = express();
const router = express.Router();
mongoose.Promise = global.Promise;

app.use(express.json());

router.post("/add", (req, res) => {
    const username = req.body.username;
    console.log(username);
    User.find({ username: username })
        .then(user => res.json(user.serialize()))
        .then(res => console.log(res));
});

module.exports = router;

使用以下架构:

const UserSchema = mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  firstName: { type: String, default: "" },
  lastName: { type: String, default: "" },
  bases: [{ type: mongoose.Schema.Types.ObjectId, ref: "UserVariables" }],
});

const UserVariables = mongoose.Schema({
  bases: { type: "String", required: true },
  users: [{ type: String }],
});
const UserVariable = mongoose.model("UserVariable", UserVariables);
const User = mongoose.model("User", UserSchema);

module.exports = { User, UserVariable };

运行服务器时,.find() 方法返回一条错误消息:TypeError: User.find is not a function。我在路由器中尝试了几个不同的版本:

router.post("/add", (req, res) => {
    const username = req.body.username;
    User.find({ username: username }, user => {
        console.log(user);
    });

还有:

User.findOne({ username: username })
        .then(user => res.json(user.serialize()))
        .then(res => console.log(res));
});

这两种方法都不起作用。在另一个应用程序中,我正在运行前者,它工作得很好。有什么想法吗?

【问题讨论】:

    标签: node.js mongodb api mongoose


    【解决方案1】:

    您正在导出一个对象:

    module.exports = { User, UserVariable };

    所以要在你的需求中使用User.find(...),你应该调用User.User.find(...)

    【讨论】:

    • 哇。很简单。将其更改为 const {User} = requires(...) 。谢谢
    【解决方案2】:

    您是否尝试过用 UserVariable 交换用户。

    UserVariable.findOne({ username: username })
            .then(user => res.json(user.serialize()))
            .then(res => console.log(res));
    });
    

    【讨论】:

    • UserVariable 不包含用户名,因此无法使用。无论如何我都试过了,它抛出了同样的错误信息
    • 问题在于User 模型被导出为对象的属性,而不是顶级对象。这只是改变了变量的名称。
    【解决方案3】:

    使用

    module.exports=User=mongoose.model('User',UserSchema)
    

    而不是

    module.exports = router;
    

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 1970-01-01
      • 2018-01-15
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      相关资源
      最近更新 更多