猫鼬字符串到 ObjectID

新手上路,请多包涵

我有带有 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

  1. 类型错误:对象函数 ObjectID(id) {
  2. TypeError:无法调用未定义的方法“ObjectId”
  3. TypeError:无法读取未定义的属性“ObjectId”

当然,我 在所有呼叫之前 都包括了猫鼬

import * as mongoose from 'mongoose';

没有任何效果。

原文由 Melixion 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 501
1 个回答

您想使用默认导出:

 import mongoose from 'mongoose';

之后, mongoose.Types.ObjectId 将起作用:

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

编辑: 完整示例(用 mongoose@4.5.5 测试):

 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
}

原文由 robertklep 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题