停止Mongoose创建自动索引

时间:2017-12-05 10:36:37

标签: node.js mongodb mongoose mongoose-schema

我试图在mongoose中创建模式,它在名为_id的mongodb中创建新索引?

 const modelSchema = new Schema({
    uid: { type: Number, required: true },
    content: {
        text: { type: String },
        attachments: [{
            type: { type: String, enum: ['IMAGE', 'VIDEO', 'POLL', 'GOAL', 'POST', 'MILESTONE', 'ARTICLE', 'DOCUMENT', 'AUDIO', 'QUOTE', 'USER', 'TIP', 'URL'] },
            object_id: { type: Number }
        }]
    },
    created: { type: String }
});

我期待这个结果:

"content" : {
"text" : "hello",
"attachments" : [ 
    {
        "type" : "IMAGE",
        "object_id" : 1
    }
]

我得到了这个结果:

"content" : {
"text" : "hello",
"attachments" : [ 
    {
        "type" : "IMAGE",
        "object_id" : 1,
        "_id" : ObjectId("5a2664fd6db6672ac43f1823")
    }
]

2 个答案:

答案 0 :(得分:2)

您可以将_id设置为false以在定义架构时禁用auto _id

var childSchema = new Schema({ name: String }, { _id: false });

检查http://mongoosejs.com/docs/guide.html#_id

答案 1 :(得分:0)

mongo将创建_id默认值,如果你想使用你自己的覆盖,你可以设置为

"_id" : 1

离 如果你插入 db.a.insert({"name":"abcd"})这将创建_id默认值 db.a.insert({"name":"abcd","_id":1})这将创建并设置_id为1