Mongoosestring到ObjectID

我有ObjectId的string。

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(); 

当我创build一个“评论”模型,并分配一个stringuser_id值或后我保存时出错。 我使console.log(comment)所有的数据被分配到variables。

我尝试:

  var str = '578df3efb618f5141202a196'; mongoose.mongo.BSONPure.ObjectID.fromHexString(str);//1 mongoose.mongo.Schema.ObjectId(str);//2 mongoose.Types.ObjectId(str);//3 
  1. TypeError:对象函数ObjectID(id){
  2. TypeError:无法调用未定义的方法“ObjectId”
  3. TypeError:无法读取未定义的属性“ObjectId”

当然,我包括猫头鹰之前所有的电话

 import * as mongoose from 'mongoose'; 

什么都没有

你想使用默认的导出:

 import mongoose from 'mongoose'; 

之后, mongoose.Types.ObjectId将工作:

 import mongoose from 'mongoose'; console.log( mongoose.Types.ObjectId('578df3efb618f5141202a196') ); 

编辑:完整的例子(用mongoose@4.5.5testing):

 import mongoose from 'mongoose'; mongoose.connect('mongodb://localhost/test'); const Schema = mongoose.Schema; 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']} }); const commentsModel = mongoose.model("comments", comments); let comment = new commentsModel; let str = '578df3efb618f5141202a196'; comment.user_id = str; comment.post = str; comment.save().then(() => console.log('saved')) .catch(e => console.log('Error', e)); 

数据库显示这个:

 mb:test$ db.comments.find().pretty() { "_id" : ObjectId("578e5cbd5b080fbfb7bed3d0"), "post" : ObjectId("578df3efb618f5141202a196"), "user_id" : ObjectId("578df3efb618f5141202a196"), "__v" : 0 } 

用这个

  var mongoose = require('mongoose'); var str = '578df3efb618f5141202a196'; var monmgoObjectId = mongoose.Types.ObjectId(str);