Mongoose nested populate virtual return null - mongodb

Why does virtual in a nested populate return null?
I have a Post schema and a User schema like this:
Post Schema:
const PostSchema = new mongoose.Schema({
_author_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
privacy: {
type: String,
default: 'public'
},
...
}, { timestamps: true, toJSON: { virtuals: true }, toObject: { getters: true, virtuals: true } });
PostSchema.virtual('author', {
ref: 'User',
localField: '_author_id',
foreignField: '_id',
justOne: true
});
module.exports = mongoose.model('Post', PostSchema);
User Schema
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
minlength: 12,
unique: true,
validate: {
validator:
(email) => {
const regex = /^\w+([.-]?\w+)*#\w+([.-]?\w+)*(\.\w{2,3})+$/;
return regex.test(email);
},
message: '{VALUE} is invalid.'
}
},
password: {
type: String,
required: true
},
username: {
type: String,
unique: true,
required: true
}
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}],
...
}, { timestamps: true, toJSON: { virtuals: true }, toObject: { getters: true, virtuals: true } });
module.exports = mongoose.model('User', UserSchema);
And when I fetch the user to DB:
const user = await User
.findOne({ username })
.populate({
path: 'posts',
model: 'Post',
select: 'description name photos comments createdAt',
options: {
limit: 3,
sort: { createdAt: -1 },
},
populate: {
path: 'author', //virtual <------- returns null but '_author_id' is fine
model: 'User',
select: 'username fullname profilePicture'
}
})
.sort('-createdAt');
Sample returned document
{
...
"posts": [
{
"photos": [],
"comments": [
"5fe96ec48564ce31dcebe669",
"5fe97c43f4169834a48b3851",
"5fe97c726ccf4633006fbeaa"
],
"description": "Gago ka ba hahahaha",
"_id": "5fe96d84178485086090faa9",
"createdAt": "2020-12-28T05:30:44.157Z",
"author": null, // <-----
"id": "5fe96d84178485086090faa9"
}
]
}
Did I miss something? My author virtual works fine in a non-nested populate.

I think you need to add author in the outer populate select.
const user = await User.findOne({ username })
.populate({
path: 'posts',
select: 'description name photos comments createdAt author', // <------- try adding author here
options: {
limit: 3,
sort: { createdAt: -1 },
},
populate: {
path: 'author',
select: 'username fullname profilePicture',
},
})
.sort('-createdAt');
Also, you shouldn't have to add the model in the populate since it already knows which model from the schema.

Related

How to I resolve below graphql query in mongodb nested array

my model schema look like this
const mongoose = require("mongoose")
const userSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
select: false,
},
email: {
type: String,
required: true,
unique: true,
match: [
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/,
"Please enter a valid email",
],
},
followers:[
{
type:mongoose.Schema.Types.ObjectId,
ref:"user"
}
],
following:[
{
type:mongoose.Schema.Types.ObjectId,
ref:"user"
}
],
displayName: {
type: String,
required: false,
},
},
{ timestamps: true }
)
module.exports = mongoose.model("user", userSchema)
in this schema all working good like mutation work fine but when i fetch query of all user then in that query followers and following field return null like bellow image
and my graphql query is
const users = {
type: new GraphQLList(UserType),
description: "Retrieves list of users",
resolve(parent, args) {
return User.find()
},
}
and typedef is
const UserType = new GraphQLObjectType({
name: "User",
description: "User types",
fields: () => ({
id: { type: GraphQLID },
username: { type: GraphQLString },
email: { type: GraphQLString },
post:{
type: GraphQLList(PostType),
resolve(parent, args) {
return Post.find({ authorId: parent.id })
},
},
savePost:{
type:GraphQLList(savedPosts1),
resolve(parent, args) {
return SavePost.findById({ authorId: parent.id })
},
},
followers:{
type:GraphQLList(UserType),
},
following:{
type:GraphQLList(UserType)
}
// displayName: { type: GraphQLString },
}),
})
so please tell me how to i resolve that followers and following query in graphql with mongodb and tell me what i write in my userType typedef

How to fetch data from multiple collections in MongoDB?

How to fetch data from multiple collections in MongoDB by using a common field and sending data (in those fetched collections) using one response?
Employee Scheema:
const mongoose = require("mongoose");
const employeeSchema = new mongoose.Schema(
{
profilePic: {
type: String,
},
employeeID: {
type: String,
required: true,
},
employeeFirstName: {
type: String,
required: true,
},
employeeLastName: {
type: String,
required: true,
},
birthday: {
type: String,
},
streetNo: {
type: String,
},
city: {
type: String,
},
phoneNumber: {
type: String,
},
jobRole: {
type: String,
required: true,
},
NIC: {
type: String,
required: true,
unique: true,
},
companyEmail: {
type: String,
required: true,
unique: true,
},
status: {
type: String,
required: true,
},
resignDate: {
type: String,
},
jobType: {
type: String,
required: true,
},
candidateID: {
type: String,
required: true,
},
teamID: {
type: String,
},
lastSeen: {
type: String,
},
token: {
type: String,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("employee", employeeSchema);
Acadamic Qualification Scheema:
const mongoose = require("mongoose");
const academicQualificaationSchema = new mongoose.Schema(
{
employeeID: {
type: String,
required: true,
},
ordinaryLevelResult: {
type: Array,
required: true,
},
advancedLevelResults: {
type: Array,
required: true,
},
achievements: {
type: Array,
required: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model(
"academicQualification",
academicQualificaationSchema
);
Professional Qualification Scheema:
const mongoose = require("mongoose");
const proffesionalQualificaationSchema = new mongoose.Schema(
{
employeeID: {
type: String,
required: true,
},
degree: {
type: Array,
required: true,
},
language: {
type: Array,
required: true,
},
course: {
type: Array,
required: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model(
"proffesionalQualification",
proffesionalQualificaationSchema
);
Controller:
exports.viewEmployees = async (req, res) => {
try {
let accQuali, profQuali;
const employees = await employeeSchema.find();
accQuali = await academicQualificaationSchema.find();
profQuali = await ProffesionalQualificationSchema.find();
if (employees || accQuali || profQuali) {
return res.status(200).json({ data: { employees, profQuali, accQuali } });
} else {
return res.status(404).json({ message: message });
}
} catch (err) {
return res.status(404).json({ err: err.message });
}
};
This controller is working properly and sends all data in 3 collections with the use of one response. But, I am comfortable if I will be able to Fetch data separately for each employee.
If you want to get the data from the three collections for specific employee or employees, you can use an aggregation pipeline with a $lookup stage, as suggested by #1sina1. For example:
db.employee.aggregate([
{
$match: {"employeeID": "IDA"}
},
{
$lookup: {
from: "academicQualification",
localField: "employeeID",
foreignField: "employeeID",
as: "academicQualification"
}
},
{
$lookup: {
from: "proffesionalQualification",
localField: "employeeID",
foreignField: "employeeID",
as: "proffesionalQualification"
}
}
])
As you can see on the playground

How to use full text search in referenced documents?

I know this was asked before, but I can't find an answer that works for me.
I have some documents, which have reference to another document, like users and orders:
Users model:
import mongoose from '../database/index.js';
import mongoosePaginate from 'mongoose-paginate-v2';
const UsersSchema = new mongoose.Schema({
user_id: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
firstName: {
type: String,
default: '',
},
lastName: {
type: String,
default: '',
},
orders: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Orders',
},
],
recipients: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Recipients',
},
],
createdAt: {
type: Date,
default: Date.now,
required: true,
select: false,
},
});
UsersSchema.index({ email: 'text', firstName: 'text', lastName: 'text' });
UsersSchema.plugin(mongoosePaginate);
UsersSchema.set('toJSON', {
virtuals: true,
});
const Users = mongoose.model('Users', UsersSchema);
export default Users;
Orders model:
import mongoose from '../database/index.js';
import mongoosePaginate from 'mongoose-paginate-v2';
import Users from './users.js';
import OrderStatus from '../enums/OrderStatusEnum.js';
const OrdersSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Users',
required: true,
},
total: {
type: Number,
required: true,
},
status: {
type: String,
enum: OrderStatus.values(),
required: true,
default: OrderStatus.CREATED,
},
payment: {
type: mongoose.Schema.Types.ObjectId,
ref: 'PaymentMethods',
required: true,
},
shortId: {
type: String,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
required: true,
},
});
OrdersSchema.index({ shortId: 'text' });
OrdersSchema.plugin(mongoosePaginate);
OrdersSchema.pre('remove', function (next) {
Users.update({ orders: this._id }, { $pull: { orders: this._id } }).exec();
next();
});
OrdersSchema.set('toJSON', {
virtuals: true,
});
const Orders = mongoose.model('Orders', OrdersSchema);
export default Orders;
I can use the $text search to query full text search from orders or users:
const orders = await Orders.paginate(
{ $text: { $search: query.filter.q } },
query.options
);
return orders;
But this will only make a search on the orders index. If, i.e., I would like to search for the order of the user whose first name is Joe, how can I make it also search in the user.firstName field, since this is a reference from Orders to Users?
I know I can't populate the fields and then search on all model, but I'm not sure how to achieve what I'm looking for.
Thanks in advance
Because full text search query must be the first stage in the aggregation pipeline, it is not currently possible to perform full text search in two collections as part of the same query.
You'll need to reorganize your data.
my requirement was to find orders of users matched with their names, partial or full-text search. the user id is ref into orders doc.
from mongodb playground:
https://mongoplayground.net/p/ASOSFvfURXW
db.inventory.aggregate([
{
"$lookup": {
"from": "orders",
"localField": "orderId",
"foreignField": "_id",
"as": "order_docs"
}
},
{
"$unwind": "$order_docs"
},
{
"$match": {
"order_docs.item": {
"$regex": "pec",
"$options": "i"
}
}
}
])

find one with multiple conditions mongoose mongodb

I am trying to obtain data from mongodb. This is the scenario. Each user has a following property(array) that takes an array of users id.
The user model is as below
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
followers: [{ type: mongoose.Types.ObjectId, ref: "user" }],
following: [{ type: mongoose.Types.ObjectId, ref: "user" }],
});
in simple terms. I need to use two conditions where postedBy: { $in: req.user.following }, or postedBy:req.user._id
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
body: {
type: String,
required: true,
},
photo: {
type: String,
required: true,
},
likes: [{ type: mongoose.Schema.ObjectId, ref: "user" }],
comments: [
{
text: String,
postedBy: { type: mongoose.Schema.Types.ObjectId, ref: "user" },
},
],
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
});
I have not figured out the second condition to add in the code below.
router.get("/getSubPost", requireLogin, async (req, res) => {
try {
const result = await Post.find({
postedBy: { $in: req.user.following },
})
.populate("postedBy", "-password")
.populate("comments.postedBy", "_id name");
res.json({ result });
} catch (error) {
console.log(error);
}
});

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);