Im currently working on adding discriminators to my express rest api. I have added different types of users to the user schema using the discriminators as different user require additional information. The problem I am facing is that when I post to the api get no errors when adding the information and only the general information is added to the schema, the details within the discriminators are ignored.
The schema is as follows:
var options = { discriminatorKey: 'type' };
var UserSchema = new Schema({
local: {
email: {
type: String,
sparse: true,
lowercase: true,
},
password: { type: String },
},
facebook: {
id: String,
token: String,
email: String,
name: String,
profileIMG: String,
},
twitter: {
id: String,
token: String,
displayName: String,
username: String
},
google: {
id: String,
token: String,
email: String,
name: String,
profileIMG: String,
}
}, options);
var addressSubschema = {
street: {
type: String,
required: true
},
number: {
type: String,
required: true
},
city: {
type: String,
required: true
},
};
var workingHoursSchema = {
start: {
type: String,
required: true
},
finish: {
type: String,
required: true
}
};
var adminSchema = new Schema({
description: {
type: String,
required: true
},
category: {
type: String,
required: true
},
workingHours: workingHoursSchema,
address: addressSubschema,
workingRadius: {
type: Number,
required: true
},
}, options);
var User = mongoose.model('User', UserSchema);
var Admin = User.discriminator('AdminUser', adminSchema);
module.exports = User;
I then export the model and when saving a new user I get a success however the admin details are not saved.
User.findOne({'local.email': email}, function(err, existingUser) {
if (err) { return next(err) }
if (existingUser) {return res.status(422).json({error: "Email already exists"})}
var user = new User({
"local.email": req.body.email,
"local.password": req.body.password,
"description": req.body.description,
"category": req.body.category,
"workingRadius": req.body.workingRadius,
"street": req.body.street,
"number": req.body.number,
"city": req.body.city,
"start": req.body.start,
"finish": req.body.finish
});
user.save(function(err) {
if (err) { return next(err) }
res.json({success: true});
});
});
Im new to using the discriminator so any help is greatly appreciated.
Related
I have three collections which are User, Profile and Userpost and all referenced accordingly. The challenge I am facing is that when I use the .populate(), instead of fetching the Profile information of the logged in user, it fetches the data of the first profile on the profile collections and it does so for any user that is logged in. Kindly help me resolve. Thanks
How I populate
router.get('/getpost/:id', (req, res) => {
const id = req.params.id;
Userpost.find({User:id}).populate('Profile').populate('User', {password: 0}).exec((err,docs) => {
if(err) throw(err);
res.json(docs);
})
});
UserpostSchema
const UserpostSchema = new Schema({
post: {
type: String,
required: true
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
required: true,
},
Profile: {
type: mongoose.Schema.Types.ObjectId,
ref: 'profile',
required: true,
}
});
const Userpost = mongoose.model('userpost', UserpostSchema);
module.exports = Userpost;
Profile
const ProfileSchema = new Schema({
lastname: {
type: String,
required: true,
},
firstname: {
type: String,
required: true,
},
othernames: {
type: String,
required: true,
},
countries: {
type: String,
required: true,
},
phones: {
type: String,
required: true,
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
required: true,
},
});
const Profile = mongoose.model('profile', ProfileSchema);
module.exports = Profile;
and User
const userSchema = new Schema({
username: {
type: String,
required: true
},
roles: {
User: {
type: Number,
default: 2001
},
Mentor: Number,
Admin: Number
},
password: {
type: String,
required: true
},
userID: {
type: String,
required: true
},
refreshToken: String
});
const User = mongoose.model('user', userSchema);
module.exports = User;
Hello since there is not subcollections in mongodb i have found that you can nest document as an array ! i did that and it worked but what i want is to add a field to that existing array without losing the old ones ! i can do that by fetching the old array and adding the new field to it and returning that array but doing the fetch inside the patch method wouldn't be a good approach ! so is there any other way i can make that happen ?
Modal :
const mongoose = require("mongoose");
const notificationSchema = new mongoose.Schema(
{
notificationType: {
type: String,
required: false,
},
message: { type: String, required: true },
},
{
timestamps: true,
}
);
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
passwordHash: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
isAdmin: {
type: Boolean,
default: false,
},
street: {
type: String,
default: "",
},
notifications: [notificationSchema],
apartment: {
type: String,
default: "",
},
zip: {
type: String,
default: "",
},
city: {
type: String,
default: "",
},
country: {
type: String,
default: "",
},
});
exports.User = mongoose.model("User", userSchema);
exports.Notification = mongoose.model("Notification", notificationSchema);
router.patch("/:id", async (req, res) => {
try {
console.log("hh");
const user = await User.findByIdAndUpdate(req.params.id, {
notifications: [
{
notificationType: "Order",
message: "New Notification",
},
],
});
if (!user) {
return res.status(404).send("The user cannot be found");
}
res.send(user);
} catch (error) {
return res.status(400).json({ success: false, error });
}
});
I have a model defined as so:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const feedbackSchema = new Schema({
Name: {
type: String,
required: true,
},
Email: {
type: String,
required: true,
},
Project: {
type: String,
required: true,
},
Wonder: {
type: String,
required: true,
},
Share: {
type: String,
required: true,
},
Delight: {
type: String,
required: true,
},
Suggestions: {
type: String,
required: true,
},
Rating: {
type: String,
required: true,
},
dateCreated: {
type: Date,
default: Date.now(),
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
});
const UserSchema = new Schema({
googleId: {
type: String
},
displayName: {
type: String
},
firstName: {
type: String
},
lastName: {
type: String
},
image: {
type: String
},
createdAt: {
type: Date,
default: Date.now(),
},
feedback: [feedbackSchema],
})
module.exports = mongoose.model("User", UserSchema);
An example document:
{
_id: ObjectId('60b9dc728a516a4669b40dbc'),
createdAt: ISODate('2021-06-04T07:42:01.992Z'),
googleId: '2342987239823908423492837',
displayName: 'User Name',
firstName: 'User',
lastName: 'Name',
image: 'https://lh3.googleusercontent.com/a-/89wf323wefiuhh3f9hwerfiu23f29h34f',
feedback: [
{
dateCreated: ISODate('2021-06-04T07:42:01.988Z'),
_id: ObjectId('60b9dc858a516a4669b40dbd'),
Name: 'Joe Bloggs',
Email: 'joe#bloggs.com',
Project: 'Some Project',
Suggestions: 'Here are some suggestions',
Rating: '10'
},
{
dateCreated: ISODate('2021-06-04T08:06:44.625Z'),
_id: ObjectId('60b9df29641ab05db7aa2264'),
Name: 'Mr Bungle',
Email: 'mr#bungle',
Project: 'The Bungle Project',
Suggestions: 'Wharghable',
Rating: '8'
},
{
dateCreated: ISODate('2021-06-04T08:08:30.958Z'),
_id: ObjectId('60b9df917e85eb6066049eed'),
Name: 'Mike Patton',
Email: 'mike#patton.com',
Project: 'No More Faith',
Suggestions: 'Find the faith',
Rating: '10'
},
],
__v: 0
}
I have two routes defined, the first one is called when the user clicked a button on a feedback item on the UI which takes the user to a "are you sure you want to delete this record"-type page displaying some of the information from the selected feedback record.
A second route which, when the user clicks 'confirm' the subrecord is deleted from the document.
The problem I'm having is I can't seem to pull the feedback from the user in order to select the document by id, here's what I have so far for the confirmation route:
router.get('/delete', ensureAuth, async (req, res) => {
try {
var url = require('url');
var url_parts = url.parse(req.url, true);
var feedbackId = url_parts.query.id;
const allFeedback = await User.feedback;
const feedbackToDelete = await allFeedback.find({ _id: feedbackId });
console.log(feedbackToDelete);
res.render('delete', {
imgSrc: user.image,
displayName: user.firstName,
feedbackToDelete
});
} catch (error) {
console.log(error);
}
})
Help much appreciated
Update
You should be able to do just this:
const feedbackToDelete = await User.feedback.find({ _id: feedbackId });
Or if feedbackId is just a string, which is appears to be, you may have to do something like:
// Create an actual _id object
// That is why in your sample doc you see ObjectId('foobarbaz')
const feedbackId = new mongoose.Types.ObjectId(url_parts.query.id);
const feedbackToDelete = await User.feedback.find({ _id: feedbackId });
Original
Shouldn't this:
const allFeedback = await User.feedback; (a field)
be this:
const allFeedback = await User.feedback(); (a method/function)
?
const groupSchema = new Schema({
name: { type: String, default: "", required: true },
participants: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
});
const userSchema = new Schema({
username: { type: String, default: "", required: true },
name: { type: String, default: "", required: true },
});
I'm trying to fetch all the groups the given user is joined. This is my try
userModel.findOne({ username: data.username }, function(err, user) {
if (user) {
groupModel
.find({"participants":{"$in":[user]}
.populate('participants')
.exec(function(err, result) {
.....
}
}
});
I'm getting an empty list in for the above query
Thank you
Look like you just need to do:
groupModel.find({participants: user._id}).exec(...
I'm looking to make a populate() on a find() request but specifying multiple models, so if no occurrence is found on the first specified model the population will make on the second.
Here is an example of what I would like to do :
const userSch = new Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
mail: {
type: String,
required: true,
unique: true,
}
});
const botSch = new Schema({
username: {
type: String,
required: true,
},
token: {
type: String,
required: true,
unique: true,
},
owner: mongoose.Schema.Types.ObjectId
});
const nspSch = new Schema({
name: String,
channels: [channels],
users: [{
id: {
type: mongoose.Schema.Types.ObjectId,
},
bot: {
type: Boolean,
}
}],
});
const channels = new Schema({
name: String,
message: [{
user: {
type: Schema.Types.ObjectId,
},
content: String,
}],
});
const nsp = mongoose.model('namespace', nspSch);
const Auth = mongoose.model('users', userSch);
const BotAuth = mongoose.model('bots', botSch);
function returnMs(nspID, channelID, callback) {
nsp.findOne({'_id': nspID}).populate({
path: 'channels.message.user',
model: 'users' || 'bots',
select: '_id username',
})
.exec(function(err, r) {
...
})
}
If there is ever an npm package, or a solution or even a track to code it, please share it.
Thank you