【发布时间】:2019-03-12 21:25:27
【问题描述】:
我看过这个问题: mongoose TypeError: Schema is not a constructor
但是我仍然不能在 Mongoose 中使用模型。
当我尝试这个时:
const mongoose = require('mongoose').connect(`mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@localhost:27017/${process.env.DB_NAME}`, {useNewUrlParser: true});
const Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
var Blog = mongoose.model('Blog', blogSchema);
我收到以下错误:
TypeError: Schema is not a constructor
at module.exports (/Users/razbuchnik/Projects/taxi4you/server/resources/permissions/api/v1-update.js:30:20)
at Layer.handle [as handle_request] (/Users/razbuchnik/Projects/taxi4you/server/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/razbuchnik/Projects/taxi4you/server/node_modules/express/lib/router/route.js:137:13)
at /Users/razbuchnik/Projects/taxi4you/server/app/middlewares/permission.js:27:7
at /Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/lib/collection.js:50:5
at runInAsyncScope (/Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/lib/cursor.js:198:5)
at /Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/lib/cursor.js:205:5
at handleCallback (/Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/node_modules/mongodb/lib/utils.js:120:56)
at /Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/node_modules/mongodb/lib/cursor.js:683:5
at handleCallback (/Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/node_modules/mongodb-core/lib/cursor.js:171:5)
at nextFunction (/Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/node_modules/mongodb-core/lib/cursor.js:691:5)
at /Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/node_modules/mongodb-core/lib/cursor.js:602:7
at queryCallback (/Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/node_modules/mongodb-core/lib/cursor.js:232:18)
at /Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/node_modules/mongodb-core/lib/connection/pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
注意:这是来自 Mongoose 官方网站和 GitHub 存储库的副本。
【问题讨论】:
-
尽量不要mongoose.connect,把connect放到自己的变量上