簡體   English   中英

如何實現 mongoose 鑒別器?

[英]How to implement mongoose discriminators?

我想為我的項目使用 mongoose 鑒別器來創建一個用戶集合,其中有一個我想使用鑒別器實現的所有者文檔。 但我得到一個錯誤

throw new Error(' mongoose.model()的第二個參數應該是 ' + ^

錯誤: mongoose.model()的第二個參數應該是 Mongoose.model 處的模式或 POJO(D:\Github\Food-Delivery-Website\node_modules\mongoose\lib\index.js:473:11)在 Object。( D:\Github\Food-Delivery-Website\models\Owner.js:21:27)

代碼如下:

// This file is models/User.js
const mongoose = require('mongoose');
const { Schema } = mongoose;

const options = { discriminatorKey: 'kind' };

const UserSchema = new Schema(
  {
    userName: {
      type: String,
      required: true,
      unique: true,
    },
    restOwned: {
      // type: [Schema.Types.ObjectId],
      type: Number,
    },
  },
  options,
);

module.exports = mongoose.model('User', UserSchema);

下面是下一個文件

// This file is models/Owner.js
const mongoose = require('mongoose');
const { Schema } = mongoose;

const User = require('./User');

const OwnerSchema = User.discriminator(
  'Owner',
  new Schema({
    isOwner: {
      type: Boolean,
      required: true,
    },
    restName: {
      type: String,
      required: true,
    },
  }),
);

module.exports = mongoose.model('Owner', OwnerSchema);

然后我在 userController.js 中導入這兩個文件

//This file is controllers/userController.js

const User = require('../models/User');
const Owner = require('../models/Owner');

exports.addUser = async (req, res) => {
  try {
    const newUser = new User({
      userName: req.body.userName,
      restOwned: req.body.restOwned,
    });

    const user = await newUser.save();

    res.status(201).json({
      status: 'Success',
      user,
    });
  } catch (err) {
    res.status(500).json({
      status: 'failed',
      message: 'Server Error: Failed Storing the Data.',
      err,
    });
  }
};

exports.addOwner = async (req, res) => {
  try {
    const newOwner = new Owner({
      isOwner: req.body.isOwner,
      restName: req.body.restName,
    });

    const owner = await newOwner.save();

    res.status(201).json({
      status: 'Success',
      owner,
    });
  } catch (err) {
    res.status(500).json({
      status: 'failed',
      message: 'Server Error: Failed Storing the Data.',
      err,
    });
  }
};

我在這里做錯了什么?

在此處輸入圖像描述

Model.discriminator()方法返回 Model。

所以你可以直接導出鑒別器並將其用作 model

// This file is models/Owner.js
const mongoose = require('mongoose');
const { Schema } = mongoose;

const User = require('./User');

//Directly export the discriminator and use it as the model
module.exports = User.discriminator(
  'Owner',
  new Schema({
    isOwner: {
      type: Boolean,
      required: true,
    },
    restName: {
      type: String,
      required: true,
    },
  }),
);

//module.exports = mongoose.model('Owner', OwnerSchema);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM