Populate and only return that populated value - mongodb

I am trying to just return the populated profile document from the User Document. But I can't seem to code in the logic correctly...What is the way to go about this? I only want to select the profile field to return from the user. I thought of maybe trying .select("profile).populate({ path: "profile"}), but that didn't work either.
User.findOne({ _id: req.user._id })
.populate({ path: "profile"}) <---
.then(user => {
res.json(user);
})
.catch(() => res.json({ Error: "User Account type is not valid" }));
User Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
profile: {
type: Schema.Types.ObjectId,
refPath: "profile_type"
},
profile_type: {
type: String,
enum: ["PartnerAdminProfile", "DistrictAdminProfile", "MentorProfile"]
},
});
module.exports = User = mongoose.model("User", UserSchema);
Profile Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const PartnerAdminProfileSchema = new Schema({ <----EDIT redefined schema name
user: {
type: Schema.Types.ObjectId,
ref: "User"
},
profile_picture: {
type: Schema.Types.ObjectId,
ref: "Image",
date: {
type: Date,
default: Date.now
}
}
});
module.exports = PartnerAdminProfile = mongoose.model("PartnerAdminProfile", PartnerAdminProfilechema);
expected output:
profile: {
user: "6546556654564",
profile_picture :{url:https://test.jpg}
}

Related

How can I see the products per each category with mongoose

this is my schema for storing products using mongoose as below.
const mongoose = require("mongoose");
const mongoosePaginate = require("mongoose-paginate-v2");
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: {
type: String,
required: true,
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category",
},
productImage: {
type: String,
required: true,
},
description: {
type: String,
},
createdAt: {
type: Date,
default: new Date(),
},
deletedAt: {
type: Date,
},
});
productSchema.plugin(mongoosePaginate);
const productModel = mongoose.model("Product", productSchema, "Product");
module.exports = productModel;
and this how I have the schema for storing categories that products are related to
const mongoose = require("mongoose");
const categorySchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
product: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
});
const categoryModel = mongoose.model("Category", categorySchema, "Category");
module.exports = categoryModel;
What I donΒ΄t know is how to populate my controller.
getAll: async (req, res) => {
const limitPage = parseInt(req.query.limit, 10) || 10;
const pageChange = parseInt(req.query.page, 10) || 1;
Product.paginate({}, { limit: limitPage, page: pageChange })
.then((result) => {
return res.status(200).json({
message: "GET request to all getAllProducts",
dataCount: result.length,
result: result,
});
})
.catch((err) => {
console.log(err);
res.status(500).json({
error: err,
});
});
},
Please help, I donΒ΄t understand why it not being populated and how to see the categories displayed with the categorie they belong to.
You should probably include populate in your query like so:
...
Product.paginate({}, { limit: limitPage, page: pageChange }).populate('category')
...
Note: Are you sure you want to have a 1-1 relation between products and categories. Because this is what you achieve if you set the relation like you did on both schemas. If yes, you should find a way to ensure that this 1-1 relation is enforced each time you save or update objects.

Subdocument not being saved in its own collection - Mongoose

I found this on the documentation for mongoose:
Subdocuments have save and validate middleware just like top-level
documents. Calling save() on the parent document triggers the save()
middleware for all its subdocuments, and the same for validate()
middleware.
But that hasn't been working for me. when I call save on my parent, the subdocument doesn't get created in its own collection. Here's my code:
Cart Model
const mongoose = require("mongoose");
const cartSchema = new mongoose.Schema({
numOfSessions: {
type: Number,
required: true
},
status:{
type: String,
enum: ["completed", "active", "deleted"],
required: true
}
}, { timestamps: true, versionKey: false });
const Cart = mongoose.model('shoppingCart', cartSchema);
module.exports = Cart;
User Model
const mongoose = require("mongoose");
const Cart = require("./xxxx").schema
const Schema = mongoose.Schema;
const userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true
},
shoppingCarts: [ Cart ]
}, { timestamps: true, versionKey: false });
const User = mongoose.model('user', userSchema);
module.exports = User;
Server Side
const new_user = new User({
firstName: req.body.firstname,
lastName: req.body.lastname,
username: req.body.username,
phoneNum: req.body.phone,
userType: req.body.userType,
email: req.body.email,
password: hashedPassword
});
new_user.shoppingCarts.push(new_cart);
console.log('pushed')
new_cart.save(); //If i take out this line, this subdocument doesn't get saved
new_user.save()
.then((result) => {
console.log(result);
});
To save the subdocument, I'm having to call save on it them well. Is this how it's supposed to be? Thx :D

MongoDB Mongoose Scheme Nested Document Structure and Relations

I have a project with the following document flow.
Users -> Accounts -> Projects
Users
Users have specific roles
Accounts
CRUD conditioned by User role
Specific users will have access to individual accounts. I was thinking to add an array userGroup with user id's?
Projects
Nested under Accounts related to a single accountToken ID
CRUD conditioned by User role
Specific users will have access to individual projects.
Here are example Schema models simplified for demo purposes.
UserSchema.js:
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: [true, 'Please add an email'],
unique: true,
},
role: {
type: String,
enum: ['admin', 'user'],
default: 'user'
}
});
module.exports = mongoose.model('User', UserSchema);
AccountSchema.js:
const AccountSchema = new mongoose.Schema({
accountName: {
type: String,
},
accountToken: {
type: String
}
});
module.exports = mongoose.model('Account', AccountSchema);
ProjectSchema.js:
const ProjectSchema = new mongoose.Schema({
projectName: {
type: String,
},
projectType: String,
projectToken: String
})
module.exports = mongoose.model('Project', ProjectSchema);
I am stuck on the best way to setup nested or sub-document Schema Relations and the best way to relate the data between each other. Any guidance and suggestions would be a huge help! Thanks!!!
Try this;
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: [true, 'Please add an email'],
unique: true,
},
role: {
type: String,
enum: ['admin', 'user'],
default: 'user'
}
});
module.exports = mongoose.model('User', UserSchema);
const AccountSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
accountName: {
type: String,
},
accountToken: {
type: String
}
});
module.exports = mongoose.model('Account', AccountSchema);
const ProjectSchema = new mongoose.Schema({
accountTokenId:{
type: String
},
projectName: {
type: String,
},
projectType: String,
projectToken: String
})
module.exports = mongoose.model('Project', ProjectSchema);

missing values when saving model

When storing a new UserModel all that saves is
{ _id: 5d9e1ddf27c26e4aec7d3d20, __v: 0 }
Here is the Schema
const mongoose = require('../../db/index');
const bcrypt = require('bcryptjs');
const Schema = mongoose.Schema;
const OrganisationModel = require('../../models/organisations/index');
function hash(val) {
'use strict';
if (typeof val !== 'string') {
val = '';
}
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(val, salt);
return hash;
}
const UserSchema = new Schema({
forename: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
password: {
type: String,
required: true,
set: hash
},
email: {
type: String,
required: true,
unique: true
},
organisation: {
type: Schema.Types.ObjectId,
ref: OrganisationModel,
required: true
},
date: {
type: Date,
default: Date.now()
}
});
module.exports = UserSchema;
Here is the model
const mongoose = require('../../db/index');
const UserSchema = require('../../models/users/index');
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;
And here is the saving
const UserModel = require('../models/users/index');
const user = new UserModel({
forename: 'Tom',
surname: 'Kiernan',
password: 'test',
email: 'test#example.com',
organisation: '5d9e1a87cb220e7c64e7f8fb',
});
user.save(err => {
if( err ) {
console.log( err );
}
console.log( user );
});
Not specifically sure why it is only autogenerating the id and a version number what is happening to the rest of the info?
Also as you may notice in the code above I am error logging the save function and it is not returning any errors.
So I found my mistake because of a comment by #CuongLeNgoc
In model file I was requiring the model it's own file and trying to use it as the Schema.
Below is the updated file with notes
const mongoose = require('../../db/index');
// const UserSchema = require('../../models/users/index'); //Wrongly requiring the model again.
const UserSchema = require('../../schema/users/index'); // correctly requiring the schema
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;

Schema hasn't been registered for model :mongoose

I have a model like this
const Schema = mongoose.Schema
const fileSchema = mongoose.Schema({
ownerId: { type: Schema.Types.ObjectId },
fileTypeId: { type: Schema.Types.ObjectId },
name: { type: String },
data: { type: Schema.Types.Mixed },
fileSize: { type: Number },
isHashInBlockchain: { type: Boolean },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
})
fileSchema.virtual('file', {
ref: 'filetype',
localField: 'fileTypeId',
foreignField: '_id'
})
fileSchema.set('toObject', { virtuals: true })
fileSchema.set('toJSON', { virtuals: true })
module.exports = mongoose.model('useruploadedfiles', fileSchema)
I am referring filetype collection to this model
But when I run the following query
await File.find(query).populate({ path: 'file' }).select('_id name createdAt updatedAt').sort({ createdAt: -1 }).skip(limit * (pageNumber - 1)).limit(limit)
I am getting the following error
Schema hasn't been registered for model "filetype"
You have to import your model in your root app file.
model.js
const UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
trim: true,
},
name: {
type: String,
required: "Please supply a name",
trim: true
},
});
module.exports = mongoose.model("User", UserSchema);
app.js
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
console.error(`πŸ™… 🚫 πŸ™… 🚫 πŸ™… 🚫 πŸ™… 🚫 β†’ ${err.message}`);
});
// READY?! Let's go!
require('./models/User')
router.js
const User = mongoose.model("User");
const getUsers = async (req, res) => res.json(await User.find({}));
app.get('/users', getUsers);