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

时间:2018-09-04 08:39:11

标签: mongodb mongoose

我的架构如下:

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却没有self.assertTrue([0] * 1000 + [1] == [1] + [0] * 1000) 发生这种情况?

2 个答案:

答案 0 :(得分:1)

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

private List<object> _nodes;    // private backing field
public List<object> Nodes
{
    get
    {
        return _nodes;          // can be "gotten" by any class
    }

    private set                 // can only be set from within this class
    {
        if (value != _nodes)
        {
            // do additional logic

            _nodes = value; // set the backing variable
        }
    }
}

public void AddNode(object Node)
{
    Nodes.Add(Node);
}

public void RemoveNode(object Node)
{
    Nodes.Remove(Node);
}

这是我用来测试的代码:

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

这是执行结果:

test execution

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

  

子文档是嵌入其他文档中的文档。在猫鼬中   这意味着您可以将模式嵌套在其他模式中。猫鼬有两个   子文档的不同概念:子文档的数组和单个   嵌套的子文档。

     

每个子文档默认都有一个_id。猫鼬   文档数组具有用于搜索文档的特殊id方法   数组以查找具有给定_id的文档。

 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);
    });

猫鼬文档链接:Mongoose SubDocs

答案 1 :(得分:0)

您可以在附件数组中定义_id : false

const MessageType = {
   // ...
   attachments: [ {name: String, contentType: String, _id: false} ],
   // ...
}
相关问题