猫鼬字符串到ObjectID [英] Mongoose String to ObjectID

查看:69
本文介绍了猫鼬字符串到ObjectID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我如何使用它:

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

当我创建评论"模型并分配字符串user_id值或发布时,保存时出现错误.我使console.log(comment)所有数据都分配给vars.

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.

我尝试:

 var str = '578df3efb618f5141202a196';
    mongoose.mongo.BSONPure.ObjectID.fromHexString(str);//1
    mongoose.mongo.Schema.ObjectId(str);//2
    mongoose.Types.ObjectId(str);//3

  1. TypeError:对象函数ObjectID(id){
  2. TypeError:无法调用未定义的方法'ObjectId'
  3. TypeError:无法读取未定义的属性'ObjectId'

当然,我还包括了猫鼬在所有通话之前

And of course I included the mongoose BEFORE ALL CALLS

import * as mongoose from 'mongoose';

什么都行不通.

推荐答案

您要使用默认导出:

import mongoose from 'mongoose';

之后,mongoose.Types.ObjectId将起作用:

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

完整示例(已通过mongoose@4.5.5测试):

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));

数据库显示以下内容:

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

这篇关于猫鼬字符串到ObjectID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆