gpt4 book ai didi

javascript - Mongoose:类型错误: 'mongooseSchemahere' 不是函数

转载 作者:行者123 更新时间:2023-12-01 00:25:40 25 4
gpt4 key购买 nike

我在 models/user.js 中有以下 Mongoose 架构设置:

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({

loginId: String,
firstname: String,
lastname: String,
eMail: String,
password: String,
active: Boolean

});

module.exports = userSchema;

在我的主 app.js 中,我有以下代码:

const mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, {
useUnifiedTopology: true,
useNewUrlParser: true,
},function(err, db) {
if (err) throw err;
var dbo = db.db("db");
dbo.collection("db").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

let userSchema = require('./models/user.js');
// Get single user
app.get('/user/:id', function (req, res) {
userSchema.findById(req.params.id, (error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})

我收到标题中的错误(只需将 mongooseSchemahere 替换为 userSchema)。我做错了什么?我尝试将 userSchema 声明放在不同的地方,但没有帮助..

最佳答案

您需要使用 mongoose.connect 来处理 mongoose 模型。

进行以下更改:

1-) 像这样创建用户模型并导出:

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
loginId: String,
firstname: String,
lastname: String,
eMail: String,
password: String,
active: Boolean
});

module.exports = mongoose.model("User", userSchema);

2-) 更改您的 App.js 以使用 mongoose.connect 连接您的数据库:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const User = require("./models/user");
const url = "mongodb://localhost:27017/mydb";

const port = process.env.PORT || 3000;

app.use(express.json());

mongoose
.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
})
.catch(error => console.log(error));

现在您可以像这样创建用户:

app.post("/user", function(req, res, next) {
console.log("Req body:", req.body);
User.create(req.body)
.then(result => {
console.log({ result });
res.send(result);
})
.catch(err => {
console.log(err);
res.status(500).send("something went wrong");
});
});

通过 _id 检索用户:

app.get("/user/:id", function(req, res, next) {
User.findById(req.params.id, (error, data) => {
if (error) {
return next(error);
} else {
res.json(data);
}
});
});

按名字检索用户:(如果您想按名字查找所有用户,请将 findOne 更改为 find。):

app.get("/user/firstname/:firstname", function(req, res, next) {
console.log(req.params.firstname);
User.findOne({ firstname: req.params.firstname }, (error, data) => {
if (error) {
return next(error);
} else {
res.json(data);
}
});
});

关于javascript - Mongoose:类型错误: 'mongooseSchemahere' 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59036343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com