Using the following Group Schema , will the role.name be unique IN the group only ? I would like to be able to store the same role name into another group button in the same group ...
/**
* Role Schema
*/
const Role = new mongoose.Schema({
name: { type: String, required: true, unique: true },
description: { type: String, required: false }
});
/**
* Group Schema
*/
const GroupSchema = new mongoose.Schema({
name: { type: String, index: { unique: true, required: true, dropDups: true } },
description: { type: String, required: false },
roles: [Role],
createdAt: {
type: Date,
default: Date.now
}
});
Related
I'm trying to add multiple compound unique index in mongoose schema, but only the first schema.index() is working independent if I change the order.
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const PrivilegeSchema = new mongoose.Schema({
application: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Application',
autopopulate: true
},
section: {
type: String,
required: false
},
title: {
type: String,
required: false
},
permission: {
type: String,
required: true
},
active: {
type: Boolean,
required: true
}
});
PrivilegeSchema.index( { permission: 1, application: 1 }, { unique: true, partialFilterExpression: {active: true} } );
PrivilegeSchema.index({ section: 1, title: 1, application: 1 }, { unique: true, partialFilterExpression: {active: true} });
export { PrivilegeSchema };
How can I set both schema index
I found the issue, the existing data in the collection is restricting the index to be created. Hence the following validation is throwing.
I removed whole data from the collection and now both the index got created.
In my project, I have a user and item collection. I have maintained the active_status of users. I want to get active users' items using user and item collection.
Item Collection
const item_model =new mongoose.Schema({
user_id:{
type: mongoose.Schema.Types.ObjectId,
ref: user,
require: true,
},
category: {
type: String,
require: true,
},
name: {
type: String,
require: true,
},
price: {
type: Number,
require: true,
},
stock: {
type: Number,
require: true,
}
}
User Collection
var user = new Schema({
firstName:{
type: String,
require: true
},
lastName:{
type: String,
require: true
},
email:{
type: String,
require: true
},
password:{
type: String,
require: true
},
user_status:{
type: String,
require: true,
default: 1
}
}
can I join these two tables and get active users items?
Your Item Collection should be
const item_model =new mongoose.Schema({
user_id:{
type: mongoose.Schema.Types.ObjectId,
ref: user,
require: true,
},
category: {
type: String,
require: true,
},
name: {
type: String,
require: true,
},
price: {
type: Number,
require: true,
},
stock: {
type: Number,
require: true,
}
}
and your user collection should be
var user = new Schema({
user_id:{
type: mongoose.Schema.Types.ObjectId,
require: true,
},
firstName:{
type: String,
require: true
},
lastName:{
type: String,
require: true
},
email:{
type: String,
require: true
},
password:{
type: String,
require: true
},
user_status:{
type: String,
require: true,
default: 1
}
}
Now lets fetch the active users from the user data model
const _ = require('lodash')
const userQuery = {
user_status: 'active'
}
const activeUsers = await userDataModel.find(userQuery);
//Now extract only user_ids from activeUsers Object
if(activeUsers && activeUsers.length>0){
const user_ids = _.map(activeUsers, 'user_id');
// once you get user_ids for all active users now lets create the query to fetch items for all active users
const itemsQuery = {
user_id: {$in: user_ids}
}
const itmesData = await itemsDataModel.find(itemsQuery);
if(itmesData) {
return itmesData;
} else {
return "Items data not found"
}
} else {
return "Active users not found"
}
I am new to the backend and trying to learn by building some stuff but unfortunately, I got stuck.
I want to know if I can update a nested array of objects in Users Schema using Mongoose in an efficient and elegant way.
Users Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
gender: {
type: String,
required: true
},
password: {
type: String,
required: true
},
friends: [{}],
notifications: []
}, {timestamps: true});
module.exports = User = mongoose.model('user', UserSchema);
In the friends' field, I stored friend request with the status of pending
I want if the user whose the request was sent to, hits an endpoint, to accept the request
by changing the status from pending to success.
This is how a friend request was stored:
friendRequest = {
_id: req.user.id,
status: 'pending',
sentByMe: false,
new: true,
inbox: []
}
Thanks as you help me out!!! 🙏🙏🙏
You should first create an additional friendRequest and inbox schemas like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const InboxSchema = new Schema({
user_id: {
type: String,
required: true
},
from_id: {
type: String,
required: true
},
message: {
type: String,
required: true
},
the_date_time: {
type: Date,
required: true
}
});
mongoose.model('Inbox', InboxSchema);
const FriendRequestSchema = new Schema({
user_id: {
type: String,
required: true
},
status: {
type: String,
required: true
},
sentByMe: {
type: Boolean,
required: true,
unique: true
},
inbox: [InboxSchema]
})
mongoose.model('FriendRequests', FriendRequestSchema);
and update your Users schema:
const UserSchema = new Schema({
name: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
gender: {
type: String,
required: true
},
password: {
type: String,
required: true
},
friends: [FriendSchema],
notifications: [FriendRequestSchema]
}, {timestamps: true});
And then use the friendRequest object
friendRequest = {
_id: req.user.id,
status: 'pending',
sentByMe: false,
new: true,
inbox: []
}
to update the Users collection
Users.update({ _id: user_id }, { $push: { notifications: friendRequest } });
Whenever you have arrays of objects within collections, its best to define additional schemas. You should also consider adding indexes to your collection schemas.
Update:
A FriendSchema would look like this:
const FriendsSchema = new Schema({
friend_id: {
type: String,
required: true
},
friend_name: {
type: String,
required: true
},
friendship_made: {
type: Date,
required: true
}
// you have to define FriendSchema before you define Users since you
// now reference [FriendSchema] in UserSchema
mongoose.model('Friends', FriendSchema);
And so is personA friends with personB?
Users.findOne({ "_id": personA.id, "friends.friend_id": personB.id});
Below is my mongoose schema.
An application can have multiple incidents and subscribers. Each incident can have multiple journal updates.
Application->incident(s)->journalupdate(s)
My goal is to allow users to update an incident detail in an application. Later add a journal update to an incident in the application.
const JournalUpdateSchema = mongoose.Schema({
timeStamp: { type: Date, required: true },
owner: { type: String },
updateText: { type: String }
});
// Incident Schema
const IncidentSchema = mongoose.Schema({
incidentNum: { type: String, required: true },
incidentPriority: { type: String, required: true },
description: { type: String, required: true },
jounralUpdates: [JournalUpdateSchema]
});
//Subscriber Schema
const SubscriberSchema = mongoose.Schema({
subscriberName: { type: String },
subscriberMail: { type: String },
subscriberPhone: { type: String }
});
// Application Schema
const ApplicationSchema = mongoose.Schema({
applicationName: { type: String, required: true },
clusterName: { type: String, required: true },
ragStatus: { type: String, required: true },
incidents: [IncidentSchema],
subscribers: [SubscriberSchema]
});
I have already tried Applications.Update(), Applications.findByIdAndUpdate() methods but I cannot reach the incident level to update.
can someone help me with this please? Any help is greatly appreciated.
Thanks.
I'm using mean stack to create a hybrid app.I'm using nosql to create DB in mongoose.My DB consists of two tables one is 'donors' and another one is 'bloodGroup'.
My 'bloodGroup' schema is as follows:
module.exports = function(mongoose) {
var Schema = mongoose.Schema;
/* bloodGroup Schema */
var bloodGroupSchema = new Schema({
name: { type: String, required: true }
});
}
My 'Donor'schema is as follows:
/* Donor Schema */
var DonorSchema = new Schema({
Name: { type: String, required: true },
DOB: { type: Date, required: true, trim: true },
Sex: { type: String },
BloodGroupID: { type: Schema.Types.ObjectId, ref: 'BloodGroup', required: true },
ContactNo: { type: String, required: true },
LocationId: { type: Schema.Types.ObjectId, ref: 'Location', required:true },
EmailId: { type: String, required: true },
Password: { type: String, required: true }
});
When many donors refer to a single blood group then BloodGroup object Id error is reported.How to solve this problem?
You can refer this link for documentation: http://mongoosejs.com/docs/populate.html
Saving Refs
/* Donor Schema */
var DonorSchema = new Schema({
_id : {type: Number},
Name: { type: String, required: true },
DOB: { type: Date, required: true, trim: true },
Sex: { type: String },
BloodGroupID: { type: Schema.Types.ObjectId, ref: 'BloodGroup', required: true },
ContactNo: { type: String, required: true },
LocationId: { type: Schema.Types.ObjectId, ref: 'Location', required:true },
EmailId: { type: String, required: true },
Password: { type: String, required: true }
});
/* bloodGroup Schema */
var bloodGroupSchema = new Schema({
_bid :{ type: Number, ref: 'Donor' },
name: { type: String, required: true }
});
module.exports = mongoose.model('Donor', DonorSchema);
module.exports = mongoose.model('Blood', bloodGroupSchema);
var vidya = new Donor({ _id: 0, name: 'Vidya', sex: 'F' });
vidya.save(function (err) {
if (err) return handleError(err);
var blood = new BloodGroup({
name: 'B+',
_bid: vidya._id // assign the _id from the Donor
});
blood.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});
Mongo is not a Relational database, relation one to many does not exist in mongDB. The question is quite confusing, but following the title, you should either embed the donnors into the BloodGroup, or create an Id field unique to which you will refer and do two queries.