我知道 Mongoose 提供了一种直接的、基于架构的解决方案来为您的应用程序数据建模。它包括内置的类型转换、验证、查询构建、业务,所以这是我的代码。
我的模型具有以下架构:
const mongoose = require("mongoose");
const crypto = require("crypto");
const userSchema = new mongoose.Schema(
{
username: {
type: String,
trim: true,
required: true,
max: 32,
unique: true,
index: true,
lowercase: true,
},
name: {
type: String,
trim: true,
required: true,
max: 32,
},
email: {
type: String,
trim: true,
required: true,
unique: true,
lowercase: true,
},
profile: {
type: String,
required: true,
},
hashed_password: {
type: String,
required: true,
},
salt: {
type: String,
},
about: {
type: String,
},
role: {
type: Number,
trim: true,
},
photo: {
data: Buffer,
contentType: String,
},
resetPasswordLink: {
data: String,
default: "",
},
},
{ timestamp: true }
);
userSchema
.virtual("password")
.set(function (password) {
// create a temporary variable called _password
this._password = password;
// generate salt
this.salt = this.makeSalt();
// encryptPassword
this.hashed_password = this.encryptPassword(password);
})
.get(function () {
return this._password;
});
userSchema.methods = {
authenticate: function (plainText) {
return this.encryptPassword(plainText) == this.hashed_password;
},
encryptPassword: function (password) {
if (!password) return "";
try {
return crypto.createHmac("sha1", this.salt).update(password).digest("hex");
} catch (err) {
return "";
}
},
makeSalt: function () {
return Math.round(new Date().valueOf() * Math.random() + "");
},
};
module.exports = mongoose.model("User", userSchema);
但这返回了这个错误:
Error: Cannot find module 'mongoose'
Require stack:
- C:\Users\Jones\Desktop\multiblog\models\user.js
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\Jones\\Desktop\\multiblog\\models\\user.js',
'C:\\Users\\Jones\\Desktop\\multiblog\\controllers\\auth.js',
'C:\\Users\\Jones\\Desktop\\multiblog\\backend\\routes\\auth.js',
'C:\\Users\\Jones\\Desktop\\multiblog\\backend\\server.js'
知道我在这里遗漏了什么吗?我保证我的 package.json
安装了猫鼬。
我还查看了架构的其他文件和结构,结果很好。
你认为我的错误是什么?
更新:package.json
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-jwt": "^6.0.0",
"express-validator": "^6.10.0",
"formidable": "^1.2.2",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"mongoose": "^5.12.3",
"morgan": "^1.10.0",
"nodemon": "^2.0.7",
"shortid": "^2.2.16",
"slugify": "^1.5.0",
"string-strip-html": "^8.2.12"
}
}
答案 0 :(得分:1)
rm -rf node_modules package-lock.json && npm install && npm start
如果这不起作用,我很确定您的某些文件夹位于您正在处理 Mongo 或 express 应用的当前文件夹之外。