Mongoose String to ObjectID

时间:2016-07-18 21:33:01

标签: node.js mongodb mongoose

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

当我创建&#34;评论&#34;模型和分配字符串user_id值或发布我保存时出错。我将console.log(comment)所有数据分配给变量。

我试试:

 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:无法调用方法&#39; ObjectId&#39;未定义的
  3. TypeError:无法读取属性&#39; ObjectId&#39;未定义的
  4. 当然我包括猫鼬所有呼叫

    import * as mongoose from 'mongoose';
    

    无效。

2 个答案:

答案 0 :(得分:14)

您想使用默认导出:

import mongoose from 'mongoose';

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

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

编辑:完整示例(使用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
}

答案 1 :(得分:4)

使用此

 var mongoose = require('mongoose');
 var str = '578df3efb618f5141202a196';
 var mongoObjectId = mongoose.Types.ObjectId(str);
相关问题