How to define a unique field in mongoose schema? - mongodb

My Schema is like below:
const schema = new mongoose.Schema({
a: {
b: { type: String, unique: true },
c: { type: String }
},
aa: {
bb: [{
cc: { type: String, unique: true },
dd: { type: String }
}]
}
})
now I want to 'b' and 'cc' fields be unique.
how can i do this?
I added this code at the end of the top code, but the schema allows duplicate values.
schema.index({'a.b':1}, {unique:true})
schema.index({'aa.bb.cc':1, {unique:true})
Do you have any idea to solve this problem?

try adding dropDups as shown below.
const schema = new mongoose.Schema({
a: {
b: { type: String, unique: true, dropDups: true },
c: { type: String }
},
aa: {
bb: [{
cc: { type: String, unique: true, dropDups: true },
dd: { type: String }
}]
}
})
if it doesn't work try: -
const schema = new mongoose.Schema({
a: {
b: { type: String, index: { unique: true, dropDups: true } },
c: { type: String }
},
aa: {
bb: [{
cc: { type: String, index: { unique: true, dropDups: true } },
dd: { type: String }
}]
}
})

The answer here depends on exactly what you mean by "I want to 'b' and 'cc' fields be unique."
Mongoose implements the unique constraint by creating a MongoDB index on that field with the unique:true option.
MongoDB enforces the unique option by not allowing the same value to be stored twice in the index.
When a document is written to MongoDB, it extracts the field values from the document that are required by the index, deduplicates the list, and then stores the values in the index with a pointer to the document.
This means that only 1 document may contain a specific value, but that document may contain that value many times.
For example:
If there is an index on {i:1}, these sample documents would have the following entries in the index:
Document
Index entries
{i:1}
1=>
{i:[2,3,4]
2=>
3=>
4=>
{i:[5,6,5,6,5]}
5=>
6=>
{i:[2,6]}
2=>
6=>
If the index were unique, and the documents were inserted in exactly that order, the first 3 documents would be perfectly acceptible, and the last would result in a duplicate key error.

Related

Query in command must target single shard key

I have an array of document ids using which I wish to delete the documents with the given id. The document id is also the shard key of the document. So I provided the following query for model.deleteMany(query)
query:
{ doc_id: { '$in': [ 'docid1', 'docid2' ] } }
I still get the error Query in command must target single shard key.
Is it possible to overcome this without looping through the array and deleting the docs one by one?
By matching any document in the collection with the _id field, you can make a query or delete command:
db.collection.deleteMany({ _id: { $exists: true }})
During the specification of the schema model in the code, a Shard Key (Partition Key) must be specified. We may execute operations such as save, update, and delete once it is provided
const mySchema = new Schema({
requestId: { type: String, required: true },
data: String,
documents: [{ docId: String, name: String, attachedBy: String }],
updatedBy: {
type: {
name: { type: String, required: true },
email: { type: String, required: true },
}, required: true
},
createdDate: { type: Date, required: true },
updatedDate: { type: Date },
}, { shardKey: { requestId: 1 } }
);

Populate without _id

I have 2 mongoose schemas, one for stock (info about stock) and one for trade. Where trade represents the trades of a stock (so time, volume, etc). Each stock has a symbol code and the data feed that I get the trades from includes the symbol codes as strings. How would I populate these two collections since I can't use the regular mongoose 'ref' here.
Here are my two schemas:
const stockSchema = new Schema({
symbolCode: { type: String, trim: true },
symbol: { type: String, trim: true },
type: { type: String, index: true, trim: true },
country: { type: String, lowercase: true }
})
const tradeSchema = new Schema({
symbolCode: { type: String, index: true },
symbol: { type: String, index: true },
price: Number,
volume: Number,
time: Date,
currency: { type: String, default: 'USD', uppercase: true, index: true }
})
I want to remove the first two fields in the trade schema so that I can just have some kind of reference to the stock here. How can I do this?
use the populate like this:
MyModel.populate([{ path: 'author', select: 'username name -_id' }]);
the -fieldName or in your case -_id will deduct it from the projection.
For future reference, I solved this using populate virtuals as follows:
stockSchema.virtual('trades', {
ref: 'Trade',
localField: 'symbolCode',
foreignField: 'symbolCode',
justOne: true
})

How to specify field which is array of objects, objects of array has one of attribute as unique but optional in Mongoose?

This is my schema for employee personal information
const mongoose = require('mongoose');
const PersonalInformationSchema = mongoose.Schema({
name: {
type: String,
required: true
},
emails: [{
email: {
type: String,
trim: true,
unique: true
},
isPrimary: {
type: Boolean
}
}]
}, {
timestamps: true
});
module.exports = mongoose.model('PersonalInformation', PersonalInformationSchema);
In my case I have array emails which is optional for employee but should be unique. When I insert a record without emails, document saves successfully (with empty array emails: []) but in next try it says
"err": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: EmployeePersonalInformation.personalinformations index: emails.email_1 dup key: { : null }"
}
You can add sparse: true to your schema, try:
const PersonalInformationSchema = mongoose.Schema({
name: {
type: String,
required: true
},
emails: [{
email: {
type: String,
trim: true,
unique: true,
sparse: true
},
isPrimary: {
type: Boolean
}
}]
}, {
timestamps: true
});
The sparse property of an index ensures that the index only contain entries for documents that have the indexed field. The index skips documents that do not have the indexed field.
So when empty documents will be skipped you won't get an error from unique constraint.

How to make sure there is no duplicate data on model's keys?

This is my user model:
const UserSchema = new mongoose.Schema(
{
email: { type: String, required: true, unique: true },
watched: [{ type: String}],
watchLater: [{ type: String}],
},
{ timestamps: true },
)
there is watched and watchLater array which contains strings. When I add a string to watched I want to remove or make sure there is no same string on watchLater and vice versa. What's the best approach for this? Do I have to query both keys separately, compare, and write back to the database or there is some other way?
You can put the criteria in query part
db.collection.update(
{ watched: { $ne: string } watchedLater: { $ne:string }},
{ $push: { watched: string }}
)

Mongoose document schema and validation

I Have a schema like so:
class Schemas
constructor: ->
#mongoose = require 'mongoose'
#schema = #mongoose.Schema
#EmployeeSchema = new #schema
'firstname': { type: String, required: true },
'lastname': { type: String, required: true },
'email': { type: String, required: true, index: { unique: true }, validate: /\b[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/ },
'departmentId': { type: #schema.ObjectId, required: true }
'enddate': String,
'active': { type: Boolean, default: true }
#EmployeeSchemaModel = #mongoose.model 'employees', #EmployeeSchema
#DepartmentSchema = new #schema
'name': { type: String, required: true, index: { unique: true } }
'employees' : [ #EmployeeSchema ]
#DepartmentSchemaModel = #mongoose.model 'departments', #DepartmentSchema
So that my employees live in an array of employee documents inside a department
I have several department documents that have a number of employee documents stored in the employees array.
I then added a new department but it contained no employees. If I then attempt to add another department without employees, Mongoose produces a Duplicate key error for the employee.email field which is a required field. The employee.email field is required and unique, and it needs to be.
Is there anyway round this?
If you enable Mongoose debug logging with the coffeescript equivalent of mongoose.set('debug', true); you can see what's going on:
DEBUG: Mongoose: employees.ensureIndex({ email: 1 }) { safe: true, background: true, unique: true }
DEBUG: Mongoose: departments.ensureIndex({ name: 1 }) { safe: true, background: true, unique: true }
DEBUG: Mongoose: departments.ensureIndex({ 'employees.email': 1 }) { safe: true, background: true, unique: true }
By embedding the full EmployeeSchema in the employees array of DepartmentSchema (rather than just an ObjectId reference to it), you end up creating unique indexes on both employees.email and department.employees.email.
So when you create a new department without any employees you are 'using up' the undefined email case in the department.employees.email index as far a uniqueness. So when you try and do that a second time that unique value is already taken and you get the Duplicate key error.
The best fix for this is probably to change DepartmentSchema.employees to an array of ObjectId references to employees instead of full objects. Then the index stays in the employees collection where it belongs and you're not duplicating data and creating opportunities for inconsistencies.
Check out these references:
http://docs.mongodb.org/manual/core/indexes/#sparse-indexes
mongoDB/mongoose: unique if not null (specifically JohnnyHK's answer)
The short of it is that since Mongo 1.8, you can define what is called a sparse index, which only kicks in the unique check if the value is not null.
In your case, you would want:
#EmployeeSchema = new #schema
'firstname': { type: String, required: true },
'lastname': { type: String, required: true },
'email': { type: String, required: true, index: { unique: true, sparse: true }, validate: /\b[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/ },
'departmentId': { type: #schema.ObjectId, required: true }
'enddate': String,
'active': { type: Boolean, default: true }
Notice the sparse: true added to your index on EmployeeSchema's email attribute.
https://gist.github.com/juanpaco/5124144
It appears that you can't create a unique index on an individual field of a sub-document. Although the db.collection.ensureIndex function in the Mongo shell appears to let you do that, it tests the sub-document as a whole for its uniqueness and not the individual field.
You can create an index on an individual field of a sub-document, you just can't make it unique.