![](/img/trans.png)
[英]Mongoose Populate returning undefined when requiring schema from another File
[英]Reusing mongoose existing schema model from one file to schema model from another file
我正在使用兩種不同類型的用戶在Node中構建Web應用程序。 它們兩者將具有共同的以及不同的屬性。 問題是我無法在另一個模型中使用常見的貓鼬模式模型。
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中使用相同的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;
問題是您沒有傳遞模式,而是傳遞了用戶模型,將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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.