2017-08-10 5 views
0

コレクションのスキーマを作成し、objectId(Stringに変換)型のドキュメントを挿入する際に、未定義の型エラーを取得しています。マングーススキーマTypeError:未定義の型ObjectIdはで。スキーマを入れ子にしましたか? refsまたは配列を使用してネストすることができます

const mongoose = require("mongoose"); 
let testSchema = new mongoose.Schema({ 
    date: {type: Date, required: true}, 
    test_id: {type: mongoose.Types.ObjectId().toString(), required: true}, 
}, {collection: 'timeslotsTest'}); 
let testModel = mongoose.model("test", testSchema); 

timeslotModel.create({ 
    "date":"2017/11/21", 
    "test_id":"1" 
} 
+2

「ObjectId()。toString()」をここで実行することはできません。 "文字列"が必要な場合は、代わりに 'type:String'です。しかし、あなたは本当に 'ObjectId'をそのまま残すべきです。余分なスペースを取らずに済むようになりました。 –

+0

ありがとうございます。私はmongoDBが初めてです。好奇心 - ObjectId型を文字列に変換できないのですか、私の方法が間違っていますか? – harzz

答えて

0

あなたは実際にidを与える必要はありません。自動的にIDを作成します。したがって、以下のサンプルが参考になります。

var UserSchema = new Schema({ 
    //username: String 
username: {type: String, unique: true} 
}); 

var JobSchema= new Schema({ 
name: String, 
members: [{type: mongoose.Schema.Types.ObjectId, ref: 'UserModel'}] 
}); 

// Mongoose Model definition 
var UserModel = mongoose.model('UserModel', UserSchema); 
var JobModel= mongoose.model('JobModel', JobSchema); 
関連する問題