我创建了一个集合,该值存储在mongodb中,如下所示。这是国家/地区集合
"_id" : ObjectId("5b851243c8352016e4b70d36"),
"is_active" : true,
"country_code" : "IND",
"country_name" : "India ",
"__v" : 0
我想使用如下所示的国家/地区集合创建状态集合
"_id" : ObjectId("5b852a6e91088217804a1996"),
"is_active" : true,
"country_id" : "India",[here i want to fetch country collection _id(objectId)]
"state_code" : "KA",
"state_name" : "Karnataka",
"__v" : 0
state.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var ObjectId = require('mongoose').Types.ObjectId
const State = new Schema({
country_id:{
type: mongoose.Schema.Types.ObjectId,
ref:'Country'
},
state_code:String,
state_name:String,
is_active:{ type: Boolean, default:true, required: true },
});
module.exports = mongoose.model('State',State);
当我传递邮递员的值时,出现如下错误
"name": "CastError",
"stringValue": "\"India\"",
"kind": "ObjectID",
"value": "India",
"path": "country_id",
我正在传递要求,正文如下所示
"country_id":"India",
"state_code":"KA",
"state_name":"Karnataka",
"is_active":true,
在mongodb中有什么方法可以定义或访问外键吗?我仍然到处搜索错误
答案 0 :(得分:0)
如下所述在文件中包含Objectid
var ObjectId = require('mongodb').ObjectID;
然后,您必须通过如下所述的req.body
"country_id": ObjectId("5b851243c8352016e4b70d36"),
"state_code":"KA",
"state_name":"Karnataka",
"is_active":true,