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
And of course I included the mongoose BEFORE ALL CALLS
import * as mongoose from 'mongoose';
nothing works.
An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.
It does. One part of id is a random hash and another is a unique counter common accross collections.
Mongoose Schematype is a configuration for the Mongoose model. Before creating a model, we always need to create a Schema. The SchemaType specifies what type of object is required at the given path. If the object doesn't match, it throws an error.
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 [email protected]
):
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With