大佬教程收集整理的这篇文章主要介绍了node.js – Mongoose String to ObjectID,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
var comments = new scheR_972_11845@a({ user_id: { type: scheR_972_11845@a.Types.ObjectId,ref: 'users',required: [true,'No user id found']},post: { type: scheR_972_11845@a.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.scheR_972_11845@a.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 scheR_972_11845@a = mongoose.scheR_972_11845@a; var comments = new scheR_972_11845@a({ user_id: { type: scheR_972_11845@a.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));
@H_446_7@mb:test$db.comments.find().pretty() { "_id" : ObjectId("578e5cbd5b080fbfb7bed3d0"),"post" : ObjectId("578df3efb618f5141202a196"),"user_id" : ObjectId("578df3efb618f5141202a196"),"__v" : 0 }
以上是大佬教程为你收集整理的node.js – Mongoose String to ObjectID全部内容,希望文章能够帮你解决node.js – Mongoose String to ObjectID所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。