【问题标题】:Next.js API RoutingNext.js API 路由
【发布时间】:2020-08-12 23:57:22
【问题描述】:

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

例如:

不起作用:

 const doc = await UserModel.findOne({ email: 'josh.mcdaniel@gmail.com' })

作品:

const doc = await req.db
    .collection('users')
    .findOne({ email: 'josh.mcdaniel@gmail.com' }) 

不起作用:

const doc = await req.db
    .collection('users')
    .find()

不确定是我做错了还是我的某些设置不正确。希望得到一些帮助。 我的用户模型供参考:

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)

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

谢谢!

【问题讨论】:

    标签: reactjs mongodb mongoose next.js


    【解决方案1】:

    尝试这样做......(这篇文章有点长,但如果你按照逻辑和导入顺序,它应该可以工作):

    示例项目结构:

    ├── .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 -- 这将建立 连接mongo 数据库 使用 >猫鼬

    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 -- 这将要求所有模型注册到数据库连接

    require("./team");
    require("./user");
    ...etc
    

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

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

    models/team.js -- 这将建立 schema 作为猫鼬 model

    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 路由中导入模型instance...

    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 -- 这将在下次加载之前建立连接池并注册模型

    require("./database"); // establishes the mongo connection
    require("./models/all"); // registers the models to the connection
    
    ...etc
    

    【讨论】:

    • 不幸的是,在过去一天尝试了这个之后,我无法让它工作。不过还是谢谢!
    • 这是一个工作回购:github.com/mattcarlotta/nextjs-ssr-kit(它有点过时,因为我没有时间更新它,但它仍然有效)。
    • 谢谢!我将在 repo 中尝试更多地使用它。
    • 在拆开我的代码并浏览你的仓库后,我得到了它的工作!非常感谢你的帮助,马特。疯狂你必须做多少才能让它与 Next js 配合得很好。
    • 很高兴我能帮上忙。在处理 SSR 时,没有什么是容易的。
    猜你喜欢
    • 2020-06-06
    • 2021-06-21
    • 2021-08-12
    • 2021-12-09
    • 1970-01-01
    • 2021-10-17
    • 2021-04-02
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多