Mongoose架构类型错误:未定义的类型`ObjectId`at。你试过嵌套模式吗?只能使用参照或阵列进行嵌套
为集合创建架构并插入objectId类型的文档(将其转换为字符串)时,出现未定义类型错误Mongoose架构类型错误:未定义的类型`ObjectId`at。你试过嵌套模式吗?只能使用参照或阵列进行嵌套,mongoose,schema,typeerror,Mongoose,Schema,Typeerror,为集合创建架构并插入objectId类型的文档(将其转换为字符串)时,出现未定义类型错误 const mongoose=require(“mongoose”); 让testSchema=newmongoose.Schema({ 日期:{type:date,必需:true}, 测试id:{type:mongoose.Types.ObjectId().toString(),必需:true}, },{collection:'timeslotsTest'}); 让testModel=mongoose.m
const mongoose=require(“mongoose”);
让testSchema=newmongoose.Schema({
日期:{type:date,必需:true},
测试id:{type:mongoose.Types.ObjectId().toString(),必需:true},
},{collection:'timeslotsTest'});
让testModel=mongoose.model(“test”,testSchema);
timeslotModel.create({
“日期”:“2017/11/21”,
“测试id”:“1”
}
您实际上不需要提供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);
我出现这个问题是因为我将
ObjectId
设置为子文档模式
import { ObjectID } from "mongodb";
const groupSchema = new Schema({
group_name: String,
members: [{
member_id: String,
member_name: String
}],
chat: [{
_id: ObjectId, //changed to 'String', resolved this issue
message: String,
sender_id: String,
status: String,
}]
})
mongoose.Types.ObjectId()
是ObjectId的构造函数,请使用
mongoose.Schema.Types.ObjectId
取而代之不,您不能在此处执行
ObjectId().toString()
。如果您需要“字符串”然后是type:String
。但是你真的应该让ObjectId
保持原样。占用的空间小得多,这样更好。谢谢。我是mongoDB的新手。好奇-是不是不能将ObjectId类型转换成String,或者我的方式不对?