Mongoose 'populate()' not populating - mongodb

So Im building a simple application with the MEARN stack.
The problem is that i want to have the user's information (name,email, etc...) to be put in the 'user' property in the product , and it's not working (Postman request return 500 status Server error) , i don't know what i'm doing wrong , thanks in advance! my code snippets :
My User Model :
const mongoose = require('mongoose')
const UserSchema = mongoose.Schema({
name : {
type: String,
required: true
},
email : {
type: String,
required: true,
unique: true
},
password : {
type: String,
required: true
},
date : {
type: Date,
default: Date.now
},
})
module.exports = mongoose.model('user',UserSchema)
my Product Model :
const mongoose = require('mongoose')
const ProductSchema = mongoose.Schema({
user:{
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name : {
type: String,
required: true
},
description : {
type: String,
required: true
},
quantity : {
type: Number,
required: true
},
price : {
type: Number,
required: true
},
date : {
type: Date,
default: Date.now
},
})
module.exports = mongoose.model('product',ProductSchema)
and my request :
router.get('/:id', async (req,res) => {
try {
const product = await Product.findById(req.params.id).populate('user')
res.json(product)
} catch (err) {
res.status(500).send('Server Error')
}
})

Your ref value needs to match the name of the model user references. So you need to change it to:
user:{
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},

You have to specify the path:populate({path:'user'}) Try :
router.get('/:id', async (req,res) => {
try {
const product = await Product.findById(req.params.id).populate({path:'user'})
res.json(product)
} catch (err) {
res.status(500).send('Server Error')
}
})

Related

MissingSchemaError: Schema hasn't been registered for model "Product"

------------------------------
Here is Order Controller
-----------------------------
import nc from "next-connect";
import db from "../../../utils/db";
import Order from "../../../models/OrderModel";
import { isAuth } from "../../../utils/auth";
const handler = nc();
handler.use(isAuth);
handler.get(async (req, res) => {
try {
await db.connect();
const order = await Order.findById(req.body.order).populate({
path: "product",
model: "Product",
});
await db.disconnect();
res.send(order);
} catch (err) {
console.log(err);
}
});
export default handler;
--------------------------------------------------------------
Here is Order Schema
--------------------------------------------------------------
import mongoose from "mongoose";
const orderSchema = new mongoose.Schema(
{
product: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
required: true,
},
],
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
}
},
{ timestamps: true }
);
const Order = mongoose.models.Order || mongoose.model("Order", orderSchema);
export default Order;
----------------------------
Here is Product Schema
----------------------------
import mongoose from "mongoose";
const productSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
category: {
type: String,
required: true,
},
period: {
type: String,
required: true,
},
features: [{ type: String, required: true }],
},
{ timestamps: true }
);
const Product =
mongoose.models.Product || mongoose.model("Product", productSchema);
export default Product;
--------------------
I am getting this error: "MissingSchemaError: Schema hasn't been registered for model "Product".
Use mongoose.model(name, schema)"
There are also some orders including product ObjectId and I am trying to get the data using populate on the POSTMAN but getting this error.
I've really searched much before posting this but I've didn't solve the error

MongoDB: Find items with the user id

I have a product collection and a user collection where I reference user to my product collection.
So far what I am trying to achieve here is to get only the products that are created by that user.
const getOwnerProduct = expressAsyncHandler(async (req, res) => {
const activeUser = await User.findById(req.user._id)
const pageSize = 10
const page = Number(req.query.pageNumber) || 1
const items = { user: { _id: activeUser } }
const count = await Product.countDocuments({ ...items } )
const products = await Product.find({ ...items }).limit(pageSize).skip(pageSize * (page - 1))
res.json({ products, page, pages: Math.ceil(count / pageSize) })
})
Here's the Product Schema:
const productSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
name: {
type: String,
required: true
},
price: {
type: Number,
required: true,
},
description: {
type: String,
required: true
},
email: {
type: String
},
rating: {
type: Number,
required: true,
default: 0
},
image: {
type: String,
required: true,
default: 0
},
}, { timestamps: true
})
And here's the userSchema:
const userSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
phone: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
role: {
type: String,
enum: ['administrator', 'productOwner', 'regular'],
default: 'regular'
}
}, { timestamps: true
})
Here's the router:
app.use('/api/products', productRoutes)
router.route('/').get(getProducts, admin).get(getOwnerProducts, productOwner)
For some reason this doesn't work. I think my query on mongodb is not correct.
Any idea what am I missing here?
Here instead of const products = await Product.find({ ...items }) you can try
await User.findById(req.user._id).forEach(element =>{Product.find({user=element._id})});
or
await User.findById(req.user._id).forEach(element =>{Product.find(user=element._id)});

graphql mongoose must be Output Type but got: undefined

schema:
const graphql = require("graphql");
const User = require("../models/user");
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema,
GraphQLID,
GraphQLList
} = graphql;
const CompanyType = new GraphQLObjectType({
name:'Company',
fields: () => ({
name: { type: GraphQLString },
catchPhrase: { type: GraphQLString },
bs: { type: GraphQLString },
})
})
const UserType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id : { type: GraphQLID },
name : { type: GraphQLString },
username : { type: GraphQLString },
email : { type: GraphQLString },
address : { type: GraphQLString },
phone : { type: GraphQLInt },
website : { type: GraphQLString },
company : new GraphQLList(CompanyType)
})
})
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
args: {
id: { type: GraphQLID }
},
resolve(parent, args){
return User.findById(args.id);
}
},
users: {
type: new GraphQLList(UserType),
resolve(parent, args){
return User.find({});
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery
});
model:
const mongoose = require('mongoose');
const Scheme = mongoose.Schema;
const userSchema = new Scheme({
id : Number,
name : String,
username : String,
email : String,
address : Object,
phone : Number,
website : String,
company : Object
})
module.exports = mongoose.model('User', userSchema)
Here i am trying to fetch data from mongodb database.
I have setup my server with expressjs with graphql and using mongoose for mongodb client.
But while making quesry in graphiql i am getting below error:
{
"errors": [
{
"message": "The type of User.company must be Output Type but got: undefined."
}
]
}
My result is with nested json so i am using GraphQLList .
Please have a look where i am doing wrong
company : {type: CompanyType}
and schema should be
const userSchema = new Scheme({
id : Number,
name : String,
username : String,
email : String,
address : Object,
phone : Number,
website : String,
company : {
name: String,
catchPhrase: String,
bs: String
}
})

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

MongoDB (mongoose) about refs

who can explain with example how to get from another schema user data (for example useravatar)
while i read about refs and i cant understand.
This is my code, but i want to send back not only article but with profile datas about author. How can i do this ? I have authorID already for this.
router.post('/get-article', (req, res) => {
const { id, authorID } = req.body.data;
Article.findByIdAndUpdate({ _id: id }, { $inc: { "pageview": 1 } }, (err, article) => {
if (err) return res.status(400).json({ NotFound: "Article Not Found" })
res.json({ article })
})
})
article schema
const schema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: { type: String, required: true },
image: { type: String, required: true },
content: { type: String, required: true },
email: { type: String, required: true },
author: { type: String, required: true, index: true },
added: { type: Date, default: Date.now },
pageview: { type: Number, default: 0 }
});
User schema
const schema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
username: { type: String, required: true },
email: { type: String, required: true },
facebookId: { type: String },
githubId: { type: String },
googleId: { type: String },
useravatar: { type: String, required: true },
userip: { type: String, required: true },
accessToken: { type: String },
date: { type: Date, default: Date.now }
});