node.js – Mongoose String to ObjectID

我有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','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(注释)所有数据都分配给了vars.

我试试:

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

> TypeError:对象函数ObjectID(id){
> TypeError:无法调用未定义的方法’ObjectId’
> TypeError:无法读取未定义的属性’ObjectId’

当然,我还包括猫鼬之前的所有电话

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测试):

import mongoose from 'mongoose';

mongoose.connect('mongodb://localhost/test');

const Schema = mongoose.Schema;

var comments = new Schema({
    user_id:  { type: Schema.Types.ObjectId,'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
}

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...