从一个文件重用mongoose现有模式模型到另一个文件重用模式模型

时间:2018-03-16 06:53:28

标签: javascript node.js mongodb mongoose mongoose-schema

我正在Node中使用两种不同类型的用户构建Web应用程序。而且它们都具有共同和不同的属性。 问题是我无法在另一个模型中使用常见的mongoose模式模型。

user.js是具有以下架构的通用模型:

//Requiring Mongoose
const mongoose = require('mongoose');

//Creating a variable to store our Schemas
const Schema = mongoose.Schema;


//Create User Schema and Model
const UserSchema = new Schema({
    email: {
        type: String,
        required: [true, 'Email Field is required'],
        unique:true,
        match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
    },
    name: {
        type: String,
        required: [true, 'Name field is required']
    },
    password: {
        type: String,
        required: [true, 'Please enter your password']
    },
    phoneNo: {
        type: String,
        required: [true, 'Phone No is required']
    }

//Create a user model which is going to represent our model in the database 
   and passing our above-created Schema
    const User = mongoose.model('user', UserSchema);

    //Exporting Models
    module.exports = User;

现在我想在另一个模型文件rider.js中使用与另一个属性familyNo相同的UserSchema 我尝试过以下方式,但失败了。

 //Requiring Mongoose
const mongoose = require('mongoose');

//Importing user Schema to remove the code redundancy
const userSchema = require('./user');

//Creating a variable to store our Schemas
const Schema = mongoose.Schema;

//Create Driver Schema and Model
const RiderSchema = new Schema({
    user: userSchema
    familyNo: {
        type: String,
        required: [true, 'Name field is required']
    }
});

//Create a rider model is going to represent our model in the database and passing our above-created Schema
const Rider = mongoose.model('rider', RiderSchema);

//Exporting Models
module.exports = Rider;

1 个答案:

答案 0 :(得分:2)

问题是你没有传递架构,你正在传递用户模型,将你的userschema移动到不同的文件中,并在两个模型中将它用作模式,这将解决问题

//Create a user model which is going to represent our model in the database  and passing our above-created Schema
const User = mongoose.model('user', UserSchema);

//Exporting Models
module.exports = User; // Here is the problem, User is a model not schema

UserSchema.js

const UserSchema = mongoose.Schema([Your Common Schema])

user.js的

var userSchema = require('./UserSchema');
module.exports = mongoose.model('User', userSchema);

OtherModel.js

var userSchema = require('./UserSchema');
module.exports = mongoose.model('OtherModel' , {
   property : String,
   user : userSchema
});