【问题标题】:How to extend schemas in Mongoose?如何在 Mongoose 中扩展模式?
【发布时间】:2018-06-05 02:53:56
【问题描述】:

我正在尝试在 Mongoose 中建立一个叠瓦模式模型,其中一些模式可以用作更复杂的模式的基础,这些模式都将共享相同的基本属性,以免对每个后续模式重复这些模式这需要它们(DRY 原则)。最终目标是将所有这些存储在同一个 MongoDB 集合下。

这是我尝试做的一个粗略的想法,使用 lodash extend:

/* Schemas */

import { Schema } from "mongoose";
import * as _ from 'lodash';

var PersonSchema: Schema = new Schema({
    email:      {type: String, required:true, unique:true},
    lastName:   {type: String, required:true},
    firstName:  {type: String, required:true}
});

export var UserSchema: Schema = _.merge( {}, PersonSchema, {
    password:   {type: String, required:true},
    versionTC:  {type: String, required:true}
});


/* Models */

import mongoose = require("mongoose");
import { Document, Model } from "mongoose";

export interface UserModel extends Document {}
export interface UserModelStatic extends Model<UserModel> {}
export const User = mongoose.model<UserModel, UserModelStatic>("User", UserSchema, "users");

然后,我使用 Node 和 Express 使用以下 POST 配置设置用户 API:

import { Response, Request, NextFunction, Router } from "express";
import { User, UserModel } from "../models/user";

// Create method
public create(req: Request, res: Response, next: NextFunction) {
    const user = new User(req.body);
    user.save().then(user => {
        res.json(user.toObject());
        next();
    }).catch(next);
}

// POST route, calling the create() method above
router.post("/users", (req: Request, res: Response, next: NextFunction) => {
    new UsersApi().create(req, res, next);
});

使用该设置,每次我尝试发布到我的 API 时忽略任一新的 UserSchema 属性(versionTC 或 password),用户仍然会保存到 Mongo,尽管它们都被定义为required: true.

但是,如果我省略了 PersonSchema 中的任何属性(firstName、lastName 或 email),POST 将按预期失败并出现 500 错误。

最后,如果我在我的 UserSchema 中定义所有 5 个属性而不使用 lodash 扩展 PersonSchema,则 POST 请求正文中的任何缺失属性都将导致 500 服务器错误(再次,正如预期的那样)。

我确信这不是 Mongoose 的问题,而且我很可能做错了什么,但我就是不知道那是什么。任何帮助将不胜感激。

【问题讨论】:

    标签: node.js mongodb typescript mongoose


    【解决方案1】:

    我最终使用了mongoose-extend-schema npm 包:

    import extendSchema = require('mongoose-extend-schema');
    
    export var UserSchema: Schema = extendSchema(PersonSchema, {
        password:   {type: String, required:true},
        versionTC:  {type: String, required:true}
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 2019-03-05
      • 2012-06-19
      • 2018-12-09
      • 2019-12-06
      • 2023-03-17
      • 2019-05-10
      相关资源
      最近更新 更多