猫鼬:.find()不是函数

时间:2018-08-11 00:19:30

标签: node.js mongodb api mongoose

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));
});

两者都不起作用。在另一个应用程序中,我正在运行前者,并且效果很好。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您要导出对象:

  

module.exports = { User, UserVariable };

因此,要根据需要使用User.find(...),请致电User.User.find(...)

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

使用

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

代替

module.exports = router;