[英]MongoDB Create New Document that references another Collection's Document IDs
I am trying to create a new document in the Form
collection.我正在尝试在Form
集合中创建一个新文档。 This document references many FormSection
documents.本文档引用了许多FormSection
文档。 Here are the Schemas:以下是架构:
const FormSchema = new Schema({
title: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true,
unique: true
},
sections: [{
type: FormSectionDetails
}],
createdDate: {
type: String,
required: false,
unique: true
},
lastEdited: {
type: String,
required: false,
unique: true
}
});
const FormSectionDetails = new Schema({
section: {
type: Schema.Types.ObjectId,
ref: 'FormSection',
required: true
},
position: {
type: Number,
required: true
}
});
const FormSectionSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
display: {
type: String,
required: true,
},
category: {
type: String,
required: true
},
...
});
let FormSection;
try {
FormSection = mongoose.connection.model('FormSection');
} catch (e) {
FormSection = mongoose.model('FormSection', FormSectionSchema);
}
However, when I try to add a new document to the Forms
collection, I get an error:但是,当我尝试将新文档添加到Forms
集合时,出现错误:
Document being inserted:正在插入的文档:
formData = {
"title": "Returning Members",
"description": "Returning Members",
"sections":
[{
"section": "6292c0fbd4837faca1d85d4d",
"position": 1
},
{
"section": "6292c0fbd4837faca1d85d4e",
"position": 2
},
...
}
Code being run:正在运行的代码:
formdata.sections.map(s => {
return {
...s,
section: ObjectId(s.section),
}}
);
return await FormSection.create(formdata);
Error message:错误信息:
ValidationError: category: Path `category` is required., display: Path `display` is required.````
Seems like it is trying to create a new FormSection document. I don't want it to create a new FormSection document. I just want it to reference existing FormSection documents using the Object IDs I specified.
The Issue seems to be with how you declare the section field in the FormSchema.问题似乎在于您如何在 FormSchema 中声明 section 字段。 Try this:尝试这个:
const FormSchema = new Schema({ title: { type: String, required: true, unique: true }, description: { type: String, required: true, unique: true }, sections: [{ type: ObjectId, ref: 'FormSectionDetails', required: true, }], createdDate: { type: String, required: false, unique: true }, lastEdited: { type: String, required: false, unique: true } });
This would just store the _ids of the existing FormSectionDetails这只会存储现有 FormSectionDetails 的 _ids
It turns out I was inserting the document into the wrong collection.事实证明我将文档插入到错误的集合中。 Instead of the code snippet:而不是代码片段:
return await FormSection.create(formdata);
It should actually be:它实际上应该是:
return await Form.create(formdata);
The error message should have been a more obvious hint for me as to what the problem was.错误消息对我来说应该是一个更明显的提示,说明问题出在哪里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.