gpt4 book ai didi

node.js - 嵌套文档中字段上的 Mongoose 索引

转载 作者:可可西里 更新时间:2023-11-01 10:02:39 24 4
gpt4 key购买 nike

我有一个小架构

var PostSchema = new mongoose.Schema({
title: String,
link: String,
author: {type:String,required:true},
upvotes: {type: Number, default: 0},
nesteddoc : {
field1: String
}
});

//This is broken - index on field1
PostSchema.index({nesteddoc.field1:1},{unique:true});

是否可以通过在 Mongoose 模式中指定而不运行 MongoDB 查询来确保索引在嵌套字段上有索引?

最佳答案

"nesteddoc.field1" 周围使用引号来评估嵌套字段:

PostSchema.index({ "nesteddoc.field1": 1 }, { unique: true });

此外,mongoose 会在内部调用 ensureIndex,从 mongoose doc :

When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. Mongoose will call ensureIndex for each index sequentially, and emit an 'index' event on the model when all the ensureIndex calls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting the autoIndex option of your schema to false, or globally on the connection by setting the option config.autoIndex to false.

你也可以在模式中定义索引:

var PostSchema = new mongoose.Schema({
title: String,
link: String,
author: { type: String, required: true },
upvotes: { type: Number, default: 0 },
nesteddoc: {
field1: { type: String, unique: true, index: true },
}
});

关于node.js - 嵌套文档中字段上的 Mongoose 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42368354/

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