Mongoose nested populate with select and limit - mongodb

How can I limit the number of pictures?
CommentBy is a ref in Comment, which is a ref in Post.
const posts = await Post.find(filter).populate({
path: 'comments',
populate: {
path: 'commentBy',
select: 'first_name last_name pictures',
},
});
Post:
const postsSchema = new Schema(
{
text: String,
comments: { type: [ObjectId], ref: 'Comment' }, // comment ref here
reactions: {
type: [ObjectId],
ref: 'Reaction',
},
},
);
Comment:
const commentsSchema = new Schema({
commentBy: {
type: ObjectId,
ref: 'User',
},
text: {
type: String,
},
});
User:
const userSchema = new Schema({
first_name: {
type: String,
},
last_name: {
type: String,
},
pictures: {
type: [String],
},
});

I don't think that in mongoose you can limit a specific field of a populated document.
You could try to use lean to return an array of objects and manipulate that in plain JS:
let posts = await Post.find(filter).populate({
path: 'comments',
populate: {
path: 'commentBy',
select: 'first_name last_name pictures',
},
}).lean().exec();
posts = posts.map((post) => {
const pics = post.comments.commentBy.pictures
if (pics.length <= 10) return post;
post.comments.commentBy.pictures = pics.slice(0, 10);
return post;
})

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.

How to populate object array in mongoose?

I wanted to populate 'item' in here and I'm getting the below error. It is an object array. This method worked for a normal array but gave an error for an object array. How to resolve it?
// Get the reserved list
const reservedDetails = await reserveInventory
.findOne({ memberID: id })
.select("itemsList")
.populate({
path: "item",
model: inventoryItem,
});
Error:
Cannot populate path `item` because it is not in your schema. Set the `strictPopulate` option to false to override.
reserveInventory Model:
const reserveInventorySchema = mongoose.Schema({
memberID: {
type: String,
ref: "member",
required: true,
},
itemsList: [
{
item: {
type: String,
ref: "inventoryItem",
},
quantity: {
type: Number,
},
},
],
});
module.exports = mongoose.model("reserveInventory", reserveInventorySchema);
inventoryItem Model:
const inventoryItemSchema = mongoose.Schema(
{
name: {
type: String,
required: true,
},
quantity: {
type: Number,
required: true,
},
available: {
type: Number,
required: true,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("inventoryItem", inventoryItemSchema);
you got it wrong here
// Get the reserved list
const reservedDetails = await reserveInventory
.findOne({ memberID: id })
.select("itemsList")
.populate({ path: "itemsList.item"});

Doubts on Mongodb query

I was designing a classifieds web app with the MERN stack. The MongoSchema is as shown below
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
books: [{
title: { type: String },
author: { type: String },
desc: { type: String },
price: { type: String },
image: { data: Buffer, contentType: String }
}],
date: {
type: Date,
default: Date.now
}
});
So all the other info except the books[] will be available after the initial sign-up, but what I want to do is to update the books array every time the user wishes to post a book for selling.
I'm planning to find the user by id, but I'm not quite sure how to add/append the info to the books array.
There are some answers to your question already in Stackoverflow.
For example:
Using Mongoose / MongoDB $addToSet functionality on array of objects
You can do something like this:
UserModel.js
const mongoose = require("mongoose");
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
books: [{
title: { type: String },
author: { type: String },
desc: { type: String },
price: { type: String },
image: { data: Buffer, contentType: String }
}],
date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model("user", userSchema);
After that, in your router file you can try something like this for the books array:
const res = await User.updateOne({ email: 'gintama#bandainamco.com' }, {'$addToSet':{
'books':{
title: "Gintama: The Final",
author: "Sorachi",
desc: "Final Arc",
price: "44.99",
image: "src"
}}); //addToSet if you don't want any duplicates in your array.
OR
const res = await User.updateOne({ email: 'gintama#bandainamco.com' }, {'$push':{
'books':{
title: "Gintama: The Final",
author: "Sorachi",
desc: "Final Arc",
price: "44.99",
image: "src"
}}); //push if duplicates are okay in your array

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 - Update Array with different types (discriminatorKey)

I have a document which can have an array of different sub documents.
Saving documents to the database work fine and the structure is exactly what I need.
My Problem is that I can not update values in the "sections" array (schema below)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const logoSchema = require('./site-sections/logo');
var sectionSchema = new Schema(
{
show: { type: Boolean, default: true },
order: Number
},
{ discriminatorKey: 'type' }
);
const siteSchema = new Schema({
_user: { type: Schema.Types.ObjectId, ref: 'User' },
type: { type: String, required: true },
title: { type: String, default: '' },
name: { type: String, required: true },
password: { type: String, default: '' },
caching: { type: Number, default: 1 },
unique_id: { type: String, required: true },
sections: [sectionSchema]
});
const sectionArray = siteSchema.path('sections');
const headerSchema = new Schema({
image: { type: String, default: '' },
title: { type: String, default: '' },
sub_title: { type: String, default: '' },
show: { type: Boolean, default: true },
logo: logoSchema
});
sectionArray.discriminator('header', headerSchema);
const textSchema = new Schema({
text: String
});
sectionArray.discriminator('text', textSchema);
module.exports = mongoose.model('site', siteSchema);
My Update function:
req.body has the following value:
{ key: 'title',
value: 'Test',
unique_site_id: '_jxn7vw' }
const Site = require('../../models/site');
exports.update = async function(req, res, next) {
console.log(req.body);
if (req.body.unique_site_id) {
Site.update(
{
unique_id: req.body.unique_site_id,
_user: req.user.id,
'sections.type': 'header'
},
{
$set: {
['sections.$.' + req.body.key]: req.body.value
}
},
function(err, status) {
if (err) {
console.log(err);
return res.status(500).send();
}
console.log(status);
return res.status(200).send();
}
);
}
};
The console.log(status) always prints: { ok: 0, n: 0, nModified: 0 }.
How can I update the title value?
Discriminator keys cannot be updated. https://github.com/Automattic/mongoose/issues/3839
Ok. So the right order is:
convert mongoose document to object with toObject()
change discriminator, and change/delete other properties
convert back to mongoose document with hydrate()
save