Unique index on nested fields in Mongoose schema - node.js

Are these schemas valid?
var StudentSchema = new mongoose.Schema({
first_name: {type: String, required:true},
last_name: {type: String, required: true},
mother_name : {type: String, required: true},
siblings:[{
name:{type: String, required: true},
age:{type:Number, required: true},
school:{type:String, required:true}
}]
});
And this
var WinSchema = new mongoose.Schema({
event:{type: mongoose.Schema.Types.ObjectId, ref:'Event'},
winners : [{
student: {type: mongoose.Schema.Types.ObjectId, ref: 'Student'},
position: {type:String, enum:["First","Second","Third","Consolation"]}
}]
});
WinSchema.index({event:1,winners.student:1},{unique:true});
mongoose.model('Win',WinSchema);
Can we nest it as shown in StudentSchema?
Can we create a unique index on nested documents?

Yes you can nest it, see schema example here and of course you can create a index on nested documents here is the example.

Related

How to create a mongoose sub model without creating a collection for it

const walletTransactionSchema = new mongoose.Schema({
a: {type: Boolean, required: true},
},
{timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}});
const walletSchema = new Schema({
b: {type: Boolean, required: true},
transactions: [{type: walletTransactionSchema}],
});
walletSchema.index({'transactions': 1}, {sparse: true});
module.exports.Wallet = mongoose.model('Wallet', walletSchema, 'wallets');
module.exports.WalletTransaction = mongoose.model('WalletTransaction', walletTransactionSchema);
I'm trying to create a model for a subdocument (WalletTransaction) without creating a collection for it. Unfortunately mongoose is automatically creating that collection. How can I prevent that behavior and just define a sub-model without creating a collection. I prefer to organize my schemas by refactoring them instead of just embedding them.
I used to do this without trouble with above definitions. I guess after updating to mongoose 6.0.8 (from 5.13) this is happend.
if you wanna create another model inside a model
You should go with the following approach
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
email: {
type: String,
required: true},
about:{type:String},
password: {type: String, required: true},
friends: [new mongoose.Schema({
user: {type: String}
}, {strict: false})],
profileImage: {type: String, default: "default.jpg"},
userName: {type: String, required: true},
matches: {type: Number, default: 0},
wins: {type: Number, default: 0},
losses: {type: Number, default: 0},
backgroundImage: {type: String, default: "default.jpg"},
resetPasswordToken: {type: String, required: false},
resetPasswordExpires: {type: Date, required: false},
isDeleted: {type: Boolean, default: false},
deletedAt: {type: Date, default: null},
}, {timestamps: true}, {strict: false});
module.exports = mongoose.model('User', userSchema);
Like this I create another model in my User model with name Friends in which each entry has one specific id

Filter by id in on one to many field

Say I have this userSchema:
const userSchema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
email: {type: String, required: true, unique: true},
});
and this chatSchema:
const chatSchema = new Schema({
user_ids: {type: [String]},
});
I wonder if I could do a search to get all chats from a user that has their user_id inside chat's user_ids and how could I do that.
If you are referencing the user schema and you just need to query the user_id you can simply do it like this:
db.chat.aggregate([{$macth:{"user_ids" : user_id}}])

Mongoose populate followers same document

I need to populate ObjectId parameters from the same Schema of users What am trying to do is I have 'Users' document and each record has followers and the ref is the same schema of users.
var userSchema = new Schema({
username: {type: String, unique: true, trim: true},
password: {type: String},
email: {type: String, trim: true},
avatar: {type: String},
fullname: {type: String},
bio: {type: String},
phone: {type: Number},
country: {type: String},
postal: {type: Number},
followers: [{ type: Schema.ObjectId, ref: 'User' }],
followed: [{ type: Schema.ObjectId, ref: 'User' }],
registered: {type: Date, default: Date.now}
});
var User = mongoose.model('users',userSchema);
Now when I tried to print the user information followers array return with ObjectId not the whole information
I try to print with this snippet
User.find().exec(function(error, groups) {
return res.status(200).send(groups);
});
What you want to achieve here is
User.find({})
.populate('followers')
.populate('followed')
.then(users => {
})
This will populate with both the followers and followed with their respective user objects

reddit comment system how to replicate in mongodb/nodejs

How do I make nested comment replies in MongoDB/mongoose to create a comment system like in reddit nesting. Here are my schemas i created so far:
var CommentSchema = Schema({
body: {type: String},
chapterId: {type: RK, ref: 'Chapter'},
by: {type: RK, ref: 'User'},
}, {timestamps: true});
var UserSchema = new Schema({
name: String,
username: {type:String, unique: true},
profile_pic: String,
password: String,
role:{type: [{
type: String,
enum: ['user', 'admin']
}],
default: ['user']
}
});

Mongodb lookup with two ObjectId

I have a little issue getting lookup to work. It returns an empty array. I use contactId field in Billing Collection. And I use the contact _id created when entry in Contact Collection in mongodb (Can see it in Robomongo). I have few Billings with ContactId corresponding to the _id of few Contacts. Is my syntaxe correct ? Do I miss something ? Thank you for your help.
Below is my lookup syntaxe
Contact.aggregate([
{
$lookup: {
from: "Billing",
localField: "_id",
foreignField: "contactId",
as: "BillingMembership"
}
}
]).exec(function (err, contacts) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Success',
obj: contacts
});
});
Below is the result I get back from the database.
(4) [Object, Object, Object, Object]
0:Object
BillingMembership:Array(0)
length:0
__proto__:Array(0)
additionalInterests:"MFM/REI"
billingEmail:"john#netdr.net"
cellPhone:6787025500
dateBirth:"1555-02-02T00:00:00.000Z"
firstName:"qtazerqr'efsg"
gogsMbrType:"Resident Applicant"
gogsYearJoined:"20111"
homePhone:6787025500
lastName:"gzaetrsg"
memberSuffix:", DO"
middleName:"fzerqgrre"
notes:"htrfjghdnt"
officeEmail:"john#netdr.net"
officePhone:6787025500
personalEmail:"john#netdr.net"
practiceId:"592e4c1638a494089c50c8c8"
praticeType:"MFM/High Risk"
spFirstNm:"gsertdhy"
spLastNm:"rthytrfgj"
spSuffix:"syhtdrh"
website:"trshdty"
__v:0
_id:"5932db29eb4dfe0de4a8a36d"
__proto__:Object
1:Object
2:Object
3:Object
Mongoose Schema Contact
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
middleName: {type: String, required: true},
lastName: {type: String, required: true},
dateBirth: {type: Date, required: true},
memberSuffix: {type: String, required: true},
officePhone: {type: Number, required: true},
homePhone: {type: Number, required: true},
cellPhone: {type: Number, required: true},
officeEmail: {type: String, required: true},
billingEmail: {type: String, required: true},
personalEmail: {type: String, required: true},
gogsMbrType: {type: String, required: true},
gogsYearJoined: {type: String, required: true},
spFirstNm: {type: String, required: true},
spLastNm: {type: String, required: true},
spSuffix: {type: String, required: true},
notes: {type: String, required: true},
praticeType: {type: String, required: true},
additionalInterests: {type: String, required: true},
website: {type: String, required: true},
practiceId: {type: Schema.Types.ObjectId, ref: 'Practice'}
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('Contact', schema);
Mongoose Schema Billing
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
reason: {type: String, required: true},
amount: {type: Number, required: true},
membership: {type: String, required: true},
membershipYear: {type: Schema.Types.ObjectId, ref: 'Membership'},
type: {type: String, required: true},
date: {type: String, required: true},
contactId: {type: Schema.Types.ObjectId, ref: 'Contact'},
conferenceId: {type: Schema.Types.ObjectId, ref: 'Conference'}
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('Billing', schema);
Solved. thanks to Veeram.
I used Change your from: "Billing" to from: "billings"

Resources