猫鼬独特:真不行 [英] mongoose unique: true not work

查看:63
本文介绍了猫鼬独特:真不行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在此脚本中猫鼬唯一不起作用

why mongoose unique not work at all in this script

  var child_process = require('child_process');
  // Load required packages
  child_process.exec("mongo test --eval 'db.users.drop();'", function(err){
  var mongoose = require('mongoose');

  console.log(mongoose.version);
  mongoose.connect('mongodb://localhost:27017/test');
  // Define our user schema

  var json = {};
  json.phone = { type: String, required: true, unique: true};
  var UserSchema = new mongoose.Schema(json);
  var Model = mongoose.model('user', UserSchema);

  var jp = new Model({ phone: "123456"});
  mongoose.connection.on('open', function(){
    console.log(jp);
    jp.save(function(err){
      console.log(err);
      var jp2 = new Model({ phone: "123456"});
      console.log(jp2);
      jp2.save(function(err){
        console.log(err);
        process.exit();
      });
    })
  });
});

我很困惑,结果就像

3.8.20
{ phone: '123456', _id: 54856cceb5b40f7a88fcc2af }
null
{ phone: '123456', _id: 54856cceb5b40f7a88fcc2b0 }
null

谢谢您的帮助.

推荐答案

之所以会发生这种情况,是因为您要在mongoose完成创建索引之前保存重复的文档.在您的应用启动后,Mongoose可以随时随地创建索引.

This happens because you're saving the duplicated document before mongoose has finished creating the index. Mongoose creates the indexes on the go, after your app has started.

因此,要确保仅在创建索引后才保存文档,您必须侦听模型的index事件.例如:

So, to ensure that your document will be saved only after the indexes were created, you have to listen to the index event of your model. For example:

Model.on('index', function (error) {
  console.log(jp);
  jp.save(function(err){
    console.log(err);
    var jp2 = new Model({ phone: "123456"});
    console.log(jp2);
    jp2.save(function(err){
      console.log(err);
      process.exit();
    });
  })
});

现在,当您尝试保存第二个文档(重复的文档)时,MongoDB将引发错误,因为您的save调用将在创建索引后立即运行.

Now, when you try to save the second document (the duplicated one), your MongoDB will raise an error, because your save calls will just run after the indexes were created.

这篇关于猫鼬独特:真不行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆