我有带有 ObjectId 的字符串。
var comments = new Schema({
user_id: { type: Schema.Types.ObjectId, ref: 'users',required: [true,'No user id found']},
post: { type: Schema.Types.ObjectId, ref: 'posts',required: [true,'No post id found']}....
export let commentsModel: mongoose.Model<any> = mongoose.model("comments", comments);
我如何使用它:
let comment = new commentsModel;
str = 'Here my ObjectId code' //
comment.user_id = str;
comment.post = str;
comment.save();
当我创建“评论”模型并分配字符串 user_id 值或发布时,我在保存时出错。我使 console.log(comment)
所有数据都分配给 vars。
我尝试:
var str = '578df3efb618f5141202a196';
mongoose.mongo.BSONPure.ObjectID.fromHexString(str);//1
mongoose.mongo.Schema.ObjectId(str);//2
mongoose.Types.ObjectId(str);//3
- 类型错误:对象函数 ObjectID(id) {
- TypeError:无法调用未定义的方法“ObjectId”
- TypeError:无法读取未定义的属性“ObjectId”
当然,我 在所有呼叫之前 都包括了猫鼬
import * as mongoose from 'mongoose';
没有任何效果。
原文由 Melixion 发布,翻译遵循 CC BY-SA 4.0 许可协议
您想使用默认导出:
之后,
mongoose.Types.ObjectId
将起作用:编辑: 完整示例(用
mongoose@4.5.5
测试):数据库显示: