Mongoose字符串到对象ID

vuv7lop3  于 2023-02-16  发布在  Go
关注(0)|答案(4)|浏览(143)

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

当我创建一个"comment"模型并分配一个字符串user_id value或post时,我在保存时遇到了一个错误。我使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){

  1. TypeError:无法调用未定义的方法"ObjectId"
  2. TypeError:无法读取未定义的属性"ObjectId"
    当然,我包括 Mongoose 在所有调用之前
import * as mongoose from 'mongoose';

什么都不管用。

0h4hbjxa

0h4hbjxa1#

要使用默认导出:

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

ymdaylpp2#

用这个

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

tyky79it3#

短代码。

const { Types } = require('mongoose');
const objectId = Types.ObjectId('62b593631f99547f8d76c339');
5jvtdoz2

5jvtdoz24#

如果您使用的是TypeScript:

const Types = require('mongoose').Types

然后:

comment.user_id = new Types.ObjectId(str)

相关问题