/ / Mongoose स्ट्रिंग टू ऑब्जेक्ट - नोड.जेएस, मोनगोडब, मोनगोज

नेवले स्ट्रिंग ObjectID-नोड. js, mongodb, नेवले

मैं 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 को सौंपा गया है।

मैं कोशिश करूँगा:

 var str = "578df3efb618f5141202a196";
mongoose.mongo.BSONPure.ObjectID.fromHexString(str);//1
mongoose.mongo.Schema.ObjectId(str);//2
mongoose.Types.ObjectId(str);//3
  1. TypeError: ऑब्जेक्ट फ़ंक्शन ऑब्जेक्ट (आईडी) {
  2. TypeError: अपरिभाषित की कॉल विधि "ObjectId" नहीं कर सकता
  3. TypeError: अपरिभाषित की "ObjectId" संपत्ति को नहीं पढ़ सकता

और निश्चित रूप से मैंने मानस को शामिल किया सभी कॉलों से पहले

import * as mongoose from "mongoose";

कुछ भी काम नहीं करता है।

उत्तर:

जवाब के लिए 8 № 1

आप डिफ़ॉल्ट निर्यात का उपयोग करना चाहते हैं:

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
}

जवाब के लिए 3 № 2

इसे इस्तेमाल करो

 var mongoose = require("mongoose");
var str = "578df3efb618f5141202a196";
var monmgoObjectId = mongoose.Types.ObjectId(str);