gpt4 book ai didi

javascript - Mongoose/Node 服务器重启并复制

转载 作者:行者123 更新时间:2023-12-02 17:10:07 25 4
gpt4 key购买 nike

好吧,经过大量的试验和错误,我确定当我删除一个集合然后通过我的应用程序重新创建它时,唯一性将不起作用,直到我重新启动本地 Node 服务器。这是我的架构

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Services = new Schema ({
type : {type : String},
subscriptionInfo : Schema.Types.Mixed,
data : Schema.Types.Mixed
},{_id:false});

var Hashtags = new Schema ({
name: {type : String},
services : [Services]
},{_id:false});

var SubscriptionSchema = new Schema ({
eventId : {type: String, index: { unique: true, dropDups: true }},
hashtags : [Hashtags]
});

module.exports = mongoose.model('Subscription', SubscriptionSchema);

这是我的路线...

router.route('/')
.post(function(req, res) {
var subscription = new subscribeModel();
subscription.eventId = eventId;
subscription.save(function(err, subscription) {
if (err)
res.send(err);
else
res.json({
message: subscription
});
});
})

如果我删除该集合,然后点击上面看到的/subscribe 端点,它将创建该条目,但不会接受重复项。直到我重新启动服务器,它才开始兑现它。有什么想法吗?谢谢!

最佳答案

当您的应用程序启动并且它本身初始化时, Mongoose 会扫描您的架构定义以查找已注册的模型并调用 .ensureIndexes()提供的参数的方法。这是"by design"行为,也包含在此声明中:

When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. 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.

所以您的一般选择是:

  1. 不要“删除”集合并调用 .remove(),这会保持索引完好无损。

  2. 手动调用.ensureIndexes()当您对集合进行放置以重建它们时。

文档中的警告一般是为大型集合创建索引可能需要一些时间并占用服务器资源。如果索引存在,这或多或少对 MongoDB 来说是“无操作”,但要注意对索引定义的微小更改,这将导致创建“附加”索引。

因此,通常最好为生产系统制定一个部署计划,您可以在其中确定需要做什么。

关于javascript - Mongoose/Node 服务器重启并复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901570/

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