[英]Allowing a Empty Object ID Mongoose,
我有兩個模型用戶和公司。 在 User I am storying the Company._ID 中,將用戶與公司相關聯。 我有兩個模型 CRUD 功能都可以工作,因為我可以創建一個用戶將其與公司相關聯,並且我可以使用我在將 company._ID 字段添加到用戶之前創建的用戶創建公司。 我的問題是,當我嘗試在我的表單中將公司字段留空時,它會拋出“用戶驗證失敗:公司:由於“BSONTypeError”而在路徑“公司”處為值“”(類型字符串)轉換為 ObjectId 失敗。
我需要一種方法,我可以先創建一個用戶,然后創建一個公司,但同時如果公司已經存在,我可以在該公司注冊。
這是我試圖根據它給我的結果以及搜索文檔得出的結論
在我的用戶 model 中,我將 required 設置為 false
const { string } = require('joi');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
const UserSchema = new Schema({
email:{
type:String,
required: true,
unique: true
},
level: String,
company: {
type: Schema.Types.ObjectId,
ref:'Companies',
required: false
},
companyName: String
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', UserSchema);
在我的表格中,我沒有驗證。
所以你得到的錯誤是在告訴你一些事情。 您沒有收到錯誤,因為您省略了該字段,您收到錯誤是因為您為該字段分配了一個空字符串。 您需要將 go 放入您創建用戶的任何位置,並且僅當公司的值是有效的 object ID 時才為公司分配一個值。
潛在問題代碼示例:
function createUser(info){
newUser = new User({email: info.email, company: info.company})
newUser.save()
}
固定代碼示例:
function createUser(info){
newUser = new User({})
if(!info.email){
throw new Error("Email must be provided")
}
newUser.email = info.email
if(info.company){
newUser.company = info.company
}
newUser.save()
}
我不確定你在哪里做這個,如果你用你用來創建用戶的文件編輯你的帖子,請對此答案發表評論,我會看看,但我保證你正在分配一個空字符串到user.company
在某些時候。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.