gpt4 book ai didi

mongodb - 嵌套对象是否自动生成ObjectId?

转载 作者:行者123 更新时间:2023-12-01 22:05:46 25 4
gpt4 key购买 nike

我的架构如下:

const MessageType = {
// ...
oAuth: { provider: String, id: String },
attachments: [ {name: String, contentType: String} ],
// ...
}
MessageSchema = new mongoose.Schema(MessageType, { timestamps: true});
Messages = mongoose.model("Message", MessageSchema);

当我使用 Messages.create 插入新的消息文档时, 一个 ObjectId ( _id ) 也为 attachments 生成, 除了我的 namecontentType字段,即:

[ { name: "xxx", contentType: "yyy", _id: zzzzzz }]

为什么会这样,对于 attachments但不是 oAuth

最佳答案

为避免生成 _id,您必须设置选项 _id: false,此外,如果您不想保存空附件对象,则需要设置 default: undefined .

const MessageTypeSchema = new  mongoose.Schema({
oAuth: {
type: String
},
attachments: {
type: [
{
type: String
}
],
_id: false,
default: undefined
}
});

这是我用来测试的代码:

 console.log('-------- Document with attachments --------');
new MessageTypeModel({
oAuth:'xxxxxxxxxxxxx',
attachments: ['teste.png','teste2.jpg']
}).save().then(result => {
console.log(result);
});

console.log('-------- Document without attachments --------');
new MessageTypeModel({
oAuth:'xxxxxxxxxxxxx'
}).save().then(result => {
console.log(result);
});

执行结果如下:

test execution

Mongoose 为单个嵌套子文档数组 创建_id,而您的对象字段oAuth 不是以下情况之一:

Subdocuments are documents embedded in other documents. In Mongoose, this means you can nest schemas in other schemas. Mongoose has two distinct notions of subdocuments: arrays of subdocuments and single nested subdocuments.

Each subdocument has an _id by default. Mongoose document arrays have a special id method for searching a document array to find a document with a given _id.

var childSchema = new Schema({ name: 'string' });

var parentSchema = new Schema({
// Array of subdocuments
children: [childSchema],
// Single nested subdocuments. Caveat: single nested subdocs only work
// in mongoose >= 4.2.0
child: childSchema
});

Mongoose 文档链接:Mongoose SubDocs

关于mongodb - 嵌套对象是否自动生成ObjectId?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52162181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com