Mongoose模式TypeError:未定义类型`ObjectId` at。你尝试过嵌套Schemas吗?您只能使用refs或数组进行嵌套

时间:2017-08-10 01:24:20

标签: mongoose schema typeerror

在创建集合模式并插入类型为objectId的文档(将其转换为String)时,获取未定义类型错误。

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"
}

3 个答案:

答案 0 :(得分:2)

你真的不需要提供身份证明。它会自动创建一个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);

答案 1 :(得分:0)

我遇到了这个问题,因为我将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,
    }]
})

答案 2 :(得分:0)

mongoose.Types.ObjectId()
是ObjectId的构造函数,请使用
改为mongoose.Schema.Types.ObjectId
Mongoose schema reference and undefined type 'ObjectID'