Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose unique: true not work [duplicate]

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();
      });
    })
  });
});

I'm quite confused, the result is like

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

Thank you for your help.

like image 506
SetupX Avatar asked Dec 08 '14 09:12

SetupX


People also ask

What does unique true do in Mongoose?

The unique option tells Mongoose that each document must have a unique value for a given path. For example, below is how you can tell Mongoose that a user's email must be unique. const mongoose = require('mongoose'); const userSchema = new mongoose.

How do I set unique fields in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

What is useCreateIndex?

the useCreateIndex option ensures that you are using the new function calls. Reference: https://mongoosejs.com/docs/connections.html#options https://mongoosejs.com/docs/deprecations.html.

What does findById return Mongoose?

Return value findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .


1 Answers

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.

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();
    });
  })
});

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.

like image 123
Rodrigo Medeiros Avatar answered Nov 15 '22 02:11

Rodrigo Medeiros