小编Mel*_*ion的帖子

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',required: [true,'No post id found']}....

export let commentsModel: mongoose.Model<any> = mongoose.model("comments", comments);
Run Code Online (Sandbox Code Playgroud)

我如何使用它:

let comment = new commentsModel;
str = 'Here my ObjectId code' //
comment.user_id = str;
comment.post = str;
comment.save();
Run Code Online (Sandbox Code Playgroud)

当我创建"注释"模型并分配字符串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
Run Code Online (Sandbox Code Playgroud)
  1. TypeError:对象函数ObjectID(id){
  2. TypeError:无法调用未定义的方法'ObjectId'
  3. TypeError:无法读取未定义的属性"ObjectId"

当然,我还包括猫鼬BEFORE ALL CALLS

import * as mongoose from 'mongoose';
Run Code Online (Sandbox Code Playgroud)

什么都行不通

mongoose mongodb node.js

10
推荐指数
2
解决办法
2万
查看次数

标签 统计

mongodb ×1

mongoose ×1

node.js ×1