admin管理员组

文章数量:1026961

I want to set primary key for two fields in a collection in mongodb through mongoose. I know to set posite primary key in mongodb as

db.yourcollection.ensureIndex( { fieldname1: 1, fieldname2: 1 }, { unique: true } )

but am using mongoose to handle mongodb I don't know how to set posite primary key from mongoose

update

I used mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true }); see my code

var mongoose = require('mongoose')

var uristring ='mongodb://localhost/fresh';
var mongoOptions = { db: { safe: true } };

// Connect to Database
mongoose.connect(uristring, mongoOptions, function (err, res) {
    if (err) {
        console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
    } else {
        console.log ('Successfully connected to: remote' + uristring);
    }
});
var mySchema = mongoose.Schema({
        ColorScaleID:String,
        UserName:String,
        Range1:Number,
    })
mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true });
var freshtime= mongoose.model("FreshTimeColorScaleInfo",mySchema)
var myVar = new freshtime({
        ColorScaleID:'red',
        UserName:'tab',
        Range1:10
    })
myVar.save()
mongoose.connection.close();

When I execute this code for first time I see a line {"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 } in mongodb's fresh database. When I execute the same code for second time I see two same lines.

{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }
{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }

If posite primary key worked then it shouldn't allow me to insert same data for second time. what would be the problem?

I want to set primary key for two fields in a collection in mongodb through mongoose. I know to set posite primary key in mongodb as

db.yourcollection.ensureIndex( { fieldname1: 1, fieldname2: 1 }, { unique: true } )

but am using mongoose to handle mongodb I don't know how to set posite primary key from mongoose

update

I used mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true }); see my code

var mongoose = require('mongoose')

var uristring ='mongodb://localhost/fresh';
var mongoOptions = { db: { safe: true } };

// Connect to Database
mongoose.connect(uristring, mongoOptions, function (err, res) {
    if (err) {
        console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
    } else {
        console.log ('Successfully connected to: remote' + uristring);
    }
});
var mySchema = mongoose.Schema({
        ColorScaleID:String,
        UserName:String,
        Range1:Number,
    })
mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true });
var freshtime= mongoose.model("FreshTimeColorScaleInfo",mySchema)
var myVar = new freshtime({
        ColorScaleID:'red',
        UserName:'tab',
        Range1:10
    })
myVar.save()
mongoose.connection.close();

When I execute this code for first time I see a line {"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 } in mongodb's fresh database. When I execute the same code for second time I see two same lines.

{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }
{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }

If posite primary key worked then it shouldn't allow me to insert same data for second time. what would be the problem?

Share Improve this question edited Apr 10, 2014 at 13:41 Guy 67.5k101 gold badges265 silver badges332 bronze badges asked Apr 10, 2014 at 12:13 nirenniren 2,7419 gold badges37 silver badges59 bronze badges 6
  • possible duplicate of Mongoose: how to define a bination of fields to be unique? – JohnnyHK Commented Apr 10, 2014 at 12:22
  • @JohnnyHK I have updated my question, can you have a look at it again. – niren Commented Apr 10, 2014 at 12:51
  • I achieved same functionality with mongodb's query in mongodb shell is db.person.ensureIndex({ ColorScaleID: 1, UserName: 1}, { unique: true }), but not with mongoose mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true }). – niren Commented Apr 10, 2014 at 13:06
  • @JohnnyHK - I don't think that it's a duplicate as he's got the definition right it's just not working for him. – Guy Commented Apr 10, 2014 at 13:41
  • @Guy - It was at the time, but it's been updated since then. – JohnnyHK Commented Apr 10, 2014 at 14:34
 |  Show 1 more ment

3 Answers 3

Reset to default 1

The way that you have defined your schema is correct and will work. What you are probably experiencing is that the database has already been created and that collection probably already exists even though it might be empty. Mongoose won't retro fit the index.

As an experiment, set your database to a DB that does not exist. e.g.:

var uristring ='mongodb://localhost/randomname';

and then try running those two lines against this database and see if you can still insert those two documents.

Then pare the contents of the "system.indexes" collection in each of those collections. You should see that the randomname db has the posite index correctly set.

As everybody mentioned, you got to use index method of a Schema to set posite unique key. But this isn't enough, try restarting MongoDB after that.

May be you can try this in your mongoose schema model,

const AppSchema1 = new Schema({
  _id         :{appId:String, name:String},
  name        : String
});

I want to set primary key for two fields in a collection in mongodb through mongoose. I know to set posite primary key in mongodb as

db.yourcollection.ensureIndex( { fieldname1: 1, fieldname2: 1 }, { unique: true } )

but am using mongoose to handle mongodb I don't know how to set posite primary key from mongoose

update

I used mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true }); see my code

var mongoose = require('mongoose')

var uristring ='mongodb://localhost/fresh';
var mongoOptions = { db: { safe: true } };

// Connect to Database
mongoose.connect(uristring, mongoOptions, function (err, res) {
    if (err) {
        console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
    } else {
        console.log ('Successfully connected to: remote' + uristring);
    }
});
var mySchema = mongoose.Schema({
        ColorScaleID:String,
        UserName:String,
        Range1:Number,
    })
mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true });
var freshtime= mongoose.model("FreshTimeColorScaleInfo",mySchema)
var myVar = new freshtime({
        ColorScaleID:'red',
        UserName:'tab',
        Range1:10
    })
myVar.save()
mongoose.connection.close();

When I execute this code for first time I see a line {"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 } in mongodb's fresh database. When I execute the same code for second time I see two same lines.

{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }
{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }

If posite primary key worked then it shouldn't allow me to insert same data for second time. what would be the problem?

I want to set primary key for two fields in a collection in mongodb through mongoose. I know to set posite primary key in mongodb as

db.yourcollection.ensureIndex( { fieldname1: 1, fieldname2: 1 }, { unique: true } )

but am using mongoose to handle mongodb I don't know how to set posite primary key from mongoose

update

I used mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true }); see my code

var mongoose = require('mongoose')

var uristring ='mongodb://localhost/fresh';
var mongoOptions = { db: { safe: true } };

// Connect to Database
mongoose.connect(uristring, mongoOptions, function (err, res) {
    if (err) {
        console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
    } else {
        console.log ('Successfully connected to: remote' + uristring);
    }
});
var mySchema = mongoose.Schema({
        ColorScaleID:String,
        UserName:String,
        Range1:Number,
    })
mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true });
var freshtime= mongoose.model("FreshTimeColorScaleInfo",mySchema)
var myVar = new freshtime({
        ColorScaleID:'red',
        UserName:'tab',
        Range1:10
    })
myVar.save()
mongoose.connection.close();

When I execute this code for first time I see a line {"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 } in mongodb's fresh database. When I execute the same code for second time I see two same lines.

{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }
{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }

If posite primary key worked then it shouldn't allow me to insert same data for second time. what would be the problem?

Share Improve this question edited Apr 10, 2014 at 13:41 Guy 67.5k101 gold badges265 silver badges332 bronze badges asked Apr 10, 2014 at 12:13 nirenniren 2,7419 gold badges37 silver badges59 bronze badges 6
  • possible duplicate of Mongoose: how to define a bination of fields to be unique? – JohnnyHK Commented Apr 10, 2014 at 12:22
  • @JohnnyHK I have updated my question, can you have a look at it again. – niren Commented Apr 10, 2014 at 12:51
  • I achieved same functionality with mongodb's query in mongodb shell is db.person.ensureIndex({ ColorScaleID: 1, UserName: 1}, { unique: true }), but not with mongoose mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true }). – niren Commented Apr 10, 2014 at 13:06
  • @JohnnyHK - I don't think that it's a duplicate as he's got the definition right it's just not working for him. – Guy Commented Apr 10, 2014 at 13:41
  • @Guy - It was at the time, but it's been updated since then. – JohnnyHK Commented Apr 10, 2014 at 14:34
 |  Show 1 more ment

3 Answers 3

Reset to default 1

The way that you have defined your schema is correct and will work. What you are probably experiencing is that the database has already been created and that collection probably already exists even though it might be empty. Mongoose won't retro fit the index.

As an experiment, set your database to a DB that does not exist. e.g.:

var uristring ='mongodb://localhost/randomname';

and then try running those two lines against this database and see if you can still insert those two documents.

Then pare the contents of the "system.indexes" collection in each of those collections. You should see that the randomname db has the posite index correctly set.

As everybody mentioned, you got to use index method of a Schema to set posite unique key. But this isn't enough, try restarting MongoDB after that.

May be you can try this in your mongoose schema model,

const AppSchema1 = new Schema({
  _id         :{appId:String, name:String},
  name        : String
});

本文标签: javascriptHow can I set composite primary key in mongodb through mongooseStack Overflow