【发布时间】: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