Reputation: 1032
None of the already existing posts on Stackoverflow have remedied my issue. I have the following in the router:
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;
with the following Schema:
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 };
When running the server, the .find() method returns an error message stating: TypeError: User.find is not a function
. I tried several different versions in the router:
router.post("/add", (req, res) => {
const username = req.body.username;
User.find({ username: username }, user => {
console.log(user);
});
as well as:
User.findOne({ username: username })
.then(user => res.json(user.serialize()))
.then(res => console.log(res));
});
Neither of which works. In another App i am running the former and it works just fine. Any ideas ?
Upvotes: 2
Views: 2001
Reputation: 101
use
module.exports=User=mongoose.model('User',UserSchema)
instead of
module.exports = router;
Upvotes: 0
Reputation: 7714
You're exporting an object:
module.exports = { User, UserVariable };
So to use User.find(...)
from your require, you should call User.User.find(...)
.
Upvotes: 2
Reputation: 585
Have you tried exchanging User with UserVariable.
UserVariable.findOne({ username: username })
.then(user => res.json(user.serialize()))
.then(res => console.log(res));
});
Upvotes: 0