23

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.

Melixion
  • 457
  • 1
  • 5
  • 17
  • 1
    Possible duplicate of [Node.js Mongoose.js string to ObjectId function](http://stackoverflow.com/questions/6578178/node-js-mongoose-js-string-to-objectid-function) – DAXaholic Jul 19 '16 at 04:27
  • No methods from that question helps ( – Melixion Jul 19 '16 at 09:26
  • Then start showing some code / error messages which should be included in your question right from the start. We cannot help you when you don't show what fails (your code) and how it fails (the error) – DAXaholic Jul 19 '16 at 09:29
  • I show code and sample of string – Melixion Jul 19 '16 at 09:37

4 Answers4

42

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
}
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • when i create "comments" model and set value i have error. `comments.user_id = mongoose.Types.ObjectId('578df3efb618f5141202a196');` `message: 'Cast to ObjectId failed for value "" at path "user_id"', name: 'CastError', type: 'ObjectId', value: '', path: 'user_id'` Mongoose see empty field... (((( – Melixion Jul 19 '16 at 10:38
  • That's a different issue (although `comments` is a schema in your example code, yet you're using it as a document?). Can you show how you create a model from the schema, how you create the document, and how you are assigning the `user_id` to it (all by editing your question)? – robertklep Jul 19 '16 at 10:42
  • add some details to question – Melixion Jul 19 '16 at 11:10
  • @Melixion `comments` is a schema, so `new comments` should fail already. It doesn't look like the actual code that you're using. – robertklep Jul 19 '16 at 11:22
  • forgot some details ) you are right ) add to question – Melixion Jul 19 '16 at 16:56
  • @Melixion I added a fully working example (for me) using your code. – robertklep Jul 19 '16 at 17:02
  • How its possible ? ( `comment.user_id = str;` without `mongoose.Types.ObjectId` i have error ((( – Melixion Jul 19 '16 at 18:10
  • @Melixion which version of Mongoose are you using? `npm ls mongoose` should show you. – robertklep Jul 19 '16 at 18:18
  • mongoose@3.8.40 ... sudo npm install mongoose... and i see you version is higher, i will try and answer about it. You can help how to install latest version of mongoose? – Melixion Jul 19 '16 at 20:52
  • @Melixion `npm install mongoose@latest` – robertklep Jul 19 '16 at 21:43
  • this help, thinks! – Melixion Jul 19 '16 at 22:53
  • I want to add that the value that you pass to this function must follow the convention for creating model ids, otherwise you will get this error... `Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters` – Alec Mather May 06 '20 at 23:53
  • 1
    @AlecDonaldMather in fact, it must be a valid string representation of an ObjectId :D – robertklep May 07 '20 at 14:02
7

use this

 var mongoose = require('mongoose');
 var str = '578df3efb618f5141202a196';
 var mongoObjectId = mongoose.Types.ObjectId(str);
Azeem Malik
  • 490
  • 3
  • 16
3

If you're using TypeScript:

const Types = require('mongoose').Types

Then:

comment.user_id = new Types.ObjectId(str)
David J
  • 1,018
  • 1
  • 9
  • 14
0

Short code.

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