Melixion
Melixion

Reputation: 517

Mongoose String to ObjectID

i have string with 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);

How i user it:

let comment = new commentsModel;
str = 'Here my ObjectId code' //
comment.user_id = str;
comment.post = str;
comment.save();

When I create a "comment" model and assign a string user_id value or post I have an error when saving. I make console.log(comment) all data is assigned to vars.

I try:

 var str = '578df3efb618f5141202a196';
    mongoose.mongo.BSONPure.ObjectID.fromHexString(str);//1
    mongoose.mongo.Schema.ObjectId(str);//2
    mongoose.Types.ObjectId(str);//3
  1. TypeError: Object function ObjectID(id) {
  2. TypeError: Cannot call method 'ObjectId' of undefined
  3. TypeError: Cannot read property 'ObjectId' of undefined

And of course I included the mongoose BEFORE ALL CALLS

import * as mongoose from 'mongoose';

nothing works.

Upvotes: 27

Views: 62400

Answers (4)

David J
David J

Reputation: 1098

If you're using TypeScript:

const Types = require('mongoose').Types

Then:

comment.user_id = new Types.ObjectId(str)

Upvotes: 4

Saif Ur Rehman
Saif Ur Rehman

Reputation: 81

Short code.

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

Upvotes: 0

Azeem Malik
Azeem Malik

Reputation: 490

use this

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

Upvotes: 7

robertklep
robertklep

Reputation: 203554

You want to use the default export:

import mongoose from 'mongoose';

After that, mongoose.Types.ObjectId will work:

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

EDIT: full example (tested with 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));

Database shows this:

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

Upvotes: 47

Related Questions