这是我的问题,我有两个架构,一个架构嵌套在另一个架构中。我试图插入数组并保存子文档,但是保存不正确,我得到了一个保存的对象,但是除了其_id之外,没有其他字段被保存。我必须先分别保存每个模型吗?这是什么问题?
这是我的两个模式:
import mongoose from "mongoose";
import {contactSchema} from "./ContactSchema"
export const bigSchema = new mongoose.Schema({
testField: {
type: String,
required: true,
},
contacts: [{ contactSchema }],
}
});
export default mongoose.model("Big", bigSchema);
import mongoose from "mongoose";
export const contactSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: number,
required: false,
}
});
export default mongoose.model("Contact", contactSchema);
这是我用来推送到联系人数组的代码。
public async saveContact(
testField: string,
name: string,
age: number,
) {
const newContact = new Contact({
name: name,
age: age,
});
console.log(newContact);
return UserContacts.findOneAndUpdate(
{
testField: testField,
},
{ $push: { contacts: newContact } },
{ new: true, upsert: true }
);
}
但是,当我检查数据库时,这就是我看到的。有一个objectId但我没有看到,这是我的“大”文档中的Contact子文档的列表
{
"_id" : ObjectId("XXXX"),
"testField" : "XXXXX",
"contacts" : [
{
"_id" : ObjectId("XXXXX")
}
],
"__v" : 0
}
答案 0 :(得分:1)
export const bigSchema = new mongoose.Schema({
testField: {
type: String,
required: true,
},
contacts: [{ contactSchema }],
}
});
应为:
export const bigSchema = new mongoose.Schema({
testField: {
type: String,
required: true,
},
contacts: [contactSchema],
}
});
尝试一下,看看会发生什么。
编辑:此外,如果您打算将contacts
用作对Contact
模型的引用数组,那么您需要这样做:
export const bigSchema = new mongoose.Schema({
testField: {
type: String,
required: true,
},
contacts: [{type: mongoose.Schema.Types.ObjectId, ref: 'Contact'}],
}
});}
这将使contacts
成为联系人ID的数组,因此您不必复制任何数据,而只是引用其集合中的联系人。 docs