Dan*_*ang 1 mongoose mongodb node.js
我试图在mongoose中为字段("event_key")创建一个唯一索引,如果我尝试创建重复条目,我希望mongodb不保存.我查看了文档,似乎我需要做的就是index: {unique: true}在模式中设置,但我似乎无法让它工作.我已经尝试了几种不同的排列,仍然无法使其发挥作用.
另外,required: true由于我可以保存条目,即使我没有传入event_key ,也似乎没有工作.我可能错过了一些非常愚蠢的东西,并想知道是否有人可以提供帮助?
架构
var WistiaAnalyticSchema = new Schema({
event_key: {type: String, required: true, index: {unique: true}},
visitor_key: String,
created: {type: Date, default: Date.now},
ip: String,
})
Run Code Online (Sandbox Code Playgroud)
试图添加到数据库
WistiaAnalytic.create({event_key: '1402230270487e0.2668362990953028'}, function(err) {});
WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {});
WistiaAnalytic.create({ip: '1402229819163e0.4385743956081569'}, function(err) {});
WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {
console.log(err)
});
Run Code Online (Sandbox Code Playgroud)
Mongoose在后台创建索引,因此您需要延迟create调用,直到索引创建完成.一种方法是使用'index'模型事件:
WistiaAnalytic.on('index', function(err) {
WistiaAnalytic.create({event_key: '1402230270487e0.2668362990953028'}, function(err) {});
WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {});
WistiaAnalytic.create({ip: '1402229819163e0.4385743956081569'}, function(err) {});
WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {
console.log(err)
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1977 次 |
| 最近记录: |