首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Next.js API路由

Next.js API路由
EN

Stack Overflow用户
提问于 2020-04-29 01:13:14
回答 1查看 1.9K关注 0票数 1

希望能从熟悉Next.js的人那里得到一些帮助。我在页面中将我的快递API路由转换到Next.js的内部API路由时遇到了问题,这看起来很有希望。问题是,它似乎不适用于我的猫鼬模型和方法。

例如:

不工作:

代码语言:javascript
复制
 const doc = await UserModel.findOne({ email: 'josh.mcdaniel@gmail.com' })

works:

代码语言:javascript
复制
const doc = await req.db
    .collection('users')
    .findOne({ email: 'josh.mcdaniel@gmail.com' }) 

不工作:

代码语言:javascript
复制
const doc = await req.db
    .collection('users')
    .find()

我不知道我是不是做错了,或者我做错了什么。希望能得到一些帮助。我的用户模型可供参考:

代码语言:javascript
复制
const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
  fullName: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  userName: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  posts: {
    type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'foodPost' }],
  },
  saves: {
    type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'foodPost' }],
  },
  photo: {
    type: String,
    default: 'https://via.placeholder.com/400',
  },
  followingCount: {
    type: Number,
    default: 0,
  },
  followerCount: {
    type: Number,
    default: 0,
  },
  following: {
    type: Array,
    default: [],
  },
  followers: {
    type: Array,
    default: [],
  },
  startDate: {
    type: Date,
    default: Date.now(),
  },
  notifications: {
    type: Array,
    default: [],
  },
})
export default mongoose.models.user || mongoose.model('user', UserSchema)

必须更改导出,以使其停止给出覆盖错误。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-29 04:03:24

试着这样做..。(这篇文章有点长,但是如果您遵循逻辑和导入顺序,它应该可以工作):

项目结构实例:

代码语言:javascript
复制
├── .next
|
├── database
|   └── index.js
|
├── models
|   ├── all.js
|   ├── index.js
|   └── teams.js
|
├── src
|   └── pages
|       ├── api
|       |   └── teams
|       |       └── names.js
|       └── index.js
|
└── next.config.json

database/index.js --这将使用mongoose建立到mongo数据库的a连接

代码语言:javascript
复制
const bluebird = require("bluebird");
const mongoose = require("mongoose");

// I use process.env.DATABASE as a flexible database name
// this can be set in an ".env" file or in your package.json scripts...
// like "dev" : "DATABASE=example-dev next dev"
const { DATABASE } = process.env;

const options = {
    useNewUrlParser: true, // avoids DeprecationWarning: current URL string parser is deprecated
    useCreateIndex: true, // avoids DeprecationWarning: collection.ensureIndex is deprecated.
    useFindAndModify: false, // avoids DeprecationWarning: collection.findAndModify is deprecated.
    useUnifiedTopology: true, // avoids DeprecationWarning: current Server Discovery and Monitoring engine is deprecated
};

// connects to a mongodb database
mongoose.connect(`mongodb://localhost/${DATABASE}`, options); 

// uses bluebird for mongoose promises
mongoose.Promise = bluebird; 

models/all.js --这将要求将所有模型都注册为,将注册到数据库连接。

代码语言:javascript
复制
require("./team");
require("./user");
...etc

models/index.js --这将导出--猫鼬模型实例(您不需要这个文件,因为您可以导入mongoose并从文件中检索model(Team),但我喜欢减少重复导入)

代码语言:javascript
复制
const { model } = require("mongoose");

module.exports = {
    Team: model("Team"),
    User: model("User"),
    ...etc
};

models/team.js --这将将模式建立为猫鼬模型

代码语言:javascript
复制
const { Schema, model } = require("mongoose");

const teamSchema = new Schema({
    league: { type: String, required: true },
    team: { type: String, unique: true },
    name: { type: String, unique: true, lowercase: true },
});

module.exports = model("Team", teamSchema);

pages/api/teams/all.js --从API路由中导入模型实例.

代码语言:javascript
复制
import { Team } from "../../../models"; (index.js)
// alternatively: 
// import { model } from "mongoose";
// cost Team = model("Team");

/**
 * Retrieves all teams names.
 *
 * @function getAllTeamNames
 * @returns {object} - names
 * @throws {string}
 */
const getAllTeamNames = async (_, res) => {
    // aggregates all team "names" into a single array, like so:
    // [{ names: ["team1,"team2","team3","team4", ...etc] }]

    const teams = await Team.aggregate([
        { $group: { _id: null, names: { $addToSet: "$team" } } },
        { $unwind: "$names" },
        { $sort: { names: 1 } },
        { $group: { _id: null, names: { $push: "$names" } } },
        { $project: { _id: 0, names: 1 } },
    ]); 

    // returns "names" array (["team1,"team2","team3","team4", ...etc])
    res.status(200).json({ names: teams[0].names });
};

export default getAllTeamNames;

next.config.js --这将在下一个加载之前建立一个连接池并注册模型。

代码语言:javascript
复制
require("./database"); // establishes the mongo connection
require("./models/all"); // registers the models to the connection

...etc
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61492595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档