sql >> Database >  >> NoSQL >> MongoDB

Mongoose String naar ObjectID

U wilt de standaard export gebruiken:

import mongoose from 'mongoose';

Daarna mongoose.Types.ObjectId zal werken:

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

BEWERKEN: volledig voorbeeld (getest met [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 toont dit:

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


  1. Verbinding met Redis-cluster mislukt

  2. MongoDB:locale::facet::_S_create_c_locale naam niet geldig

  3. hoe krijg ik sessies werkend met redis, express &socket.io?

  4. Inleiding tot Redis