I have Mongoose model:
const mongoose = require('mongoose')
const { Schema } = mongoose
const schema = new Schema({
Name: { type: String },
Category: { type: String },
Price: { type: Number }
})
module.exports = mongoose.model('Product', schema)
And I have to sort by Category field. Sort order is
['Clothes', 'Accessories', 'Footwears']
How cat I do it?
The MongoDB server doesn't offer any way to provide a custom sort function.
Javascript does, so you can get the results from the query as an array, and use a custom compare function with Array.sort
I solved it by adding weight of Category. Now my model is like this:
const schema = new Schema({
Name: { type: String },
Category: { type: String },
CategoryWeight: { type: Number },
Price: { type: Number }
})
And I sorting like this:
const products = await Product.find().sort('-CategoryWeight')
Related
name:"salman,
protein:23,
carbs:23,
calorie:1221,
fats:12,
ingredients:{
salt:1 teaspoon,
......
}
I want a schema like this how can I make a schema of this with nodejs mongoose
also how can i add data in this nested schema because am getting error
Initially you have to create the table schema like this:
const mongoose = require('mongoose');
// Health Schema
const HealthSchema = new mongoose.Schema({
name: {
type: String,
},
protein: {
type: String,
},
carbs: {
type: String,
},
calorie: {
type: String,
},
fats: {
type: String,
},
ingredients: {
type: object,
default: {
salt: '',
fibre: ''
}
},
});
module.exports = mongoose.model(
'health',
HealthSchema
);
Here ingredients objects have priorly set the keyname. So you have to just pass the value at the time of creation.
I'm gonna skip alot of things here.
In your schema do something like,
ingredients:[String]
when creating new data do something like
const healtData= await new healtData({... the data here})
the do something like this before calling save
healthData.ingredients.push(ingredient)
healthData.save()
I'm developing a web app that uses mongodb database using mongoose in node.js...
Now, I'm trying to build the rate feature, in this feature, people can rate the store and give some comments about that store.
This is the structure:
rate: {
author: req.body.author,
text: req.body.text
}
To update it I'm using the "findOneAndUpdate" function, but, Always when i do it, the existent rate is overwritten by the new... Can you guys help me?
Here you can do. I am just demonstrating with example
Model
//Model
const ratingSchema = new mongoose.Schema({
author: { type: String, required: true },
text: { type: String, required: true }
});
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
description: { type: String },
rating: [ratingSchema],
price: { type: Number, default: 1 },
});
module.exports = mongoose.model('Product', productSchema );
Now you can just push a new array
Controller
const ProductModel = require('./models/product');
const { id } = req.params;
const { author, text } = req.body;
PersonModel.update(
{ _id: id },
{ $push: { rating: { author, text }} },
done
);
More about: https://mongoosejs.com/docs/api/array.html#mongoosearray_MongooseArray-push
Try this one
The model
const schema = new mongoose.Schema({
name: String,
description: String,
price: Number,
rating: [{
author : String,
text : String
}]
});
module.exports = mongoose.model('Product', schema );
In request handler
const Product = require('./models/product');
const { id } = req.params; //product ID
const { author, text } = req.body;
const product = Product.findById(id);
product.rating = [...product.rating,{ author, text }]
product.save();
One way is with regular JS, you can simply store the document you want to update in a variable. Then, use the push method on the rate field before calling save on the variable.
I know I can use virtual in mongoose to populate without _id.
But My situation is something like this:
const storeSchema = new mongoose.Schema({
store_id: Number,
store_name: String,
cart_tokens: [String],
})
const cartSchema = new mongoose.Schema({
cart_token: String,
items: { type: Array },
})
My cart_tokens in the store schema is an array instead of one value.
I want the result of store be something like:
{
store_id: xxx,
store_name: xxx,
carts:[
{
cart_token: xxx,
items: [...],
},
{...},
{...}
]
}
Is it possible to do this?
This will work:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let cartSchema = new Schema({
cart_token: String,
items: { type: Array },
})
let storeSchema = new Schema({
store_id: Number,
store_name: String,
cart_tokens: [cartSchema]
});
module.exports = mongoose.model('Cart', cartSchema);
Here is my Game Schema :
var mongoose = require('mongoose');
const GameSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
publishers: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Publisher'
}
]
});
var GameModel = mongoose.model('Game', GameSchema);
module.exports = GameModel;
Here is my Publisher Schema :
var mongoose = require('mongoose');
const PublisherSchema = new mongoose.Schema({
companyName: {
type: String,
required: true
},
firstParty: {
type: Boolean,
required: true
},
website: {
website: String,
}
});
var PublisherModel = mongoose.model('Publisher', PublisherSchema);
module.exports = PublisherModel;
I have a picture of what you can find in my collection "games" in mongoDB :
When I use this route :
router.get('/games', async function(req, res) {
const games = await Game
.find()
.populate('publishers')
.select('title publishers')
res.json(games);
})
I have empty arrays as result for the publishers. If I don't use an array in Schema, this is correcly populated and I got data of publisher into each game. So why mongoose doesn't populate when it is an array?
Check below by modifying the schema definition as below
I think the below could fix your issue, please give a try by redefining the publishers as below
Publishers: [
publisher: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Publisher'
}
]
I think the definition of schema is more about to define the structure of the object that we would like to process, rather about the number of objects that we want to process.
The Schema definition with what I know is defining the semantics of the model and to take advantage of the middle ware functionalities.
You can save multiple objects of which meet the same semantic definition but the definition itself cannot be an array
Thanks
Pavan
Is it possible with mongoose to create a schema, call it Folders and it has a property within called subfolders that is an array of nested Folder subdocs?
const mongoose = require('mongoose')
let SubSchema = mongoose.Schema({
name: { type: String, required: true }
})
let FolderSchema = mongoose.Schema({
name: { type: String, required: true },
children: [ SubSchema ]
})
I know I can nest subdocs in an array by referencing another schema similar to what is shown above. What I'm looking to do though is reuse FolderSchema within itself. Obviously this causes an issue because at the time of creation of the schema, FolderSchema doesn't exist. Is there a better way to do this? Is there a way to recursively nest documents using the same schema?
I know I could have the array be a list of ObjectId that reference a collection but I was hoping to just keep it all nested as documents. I guess if I did populate() to let it resolve the doc ids, that would essentially be the same thing. Just wondering if there is another method I wasn't aware of.
I haven't tried this personally, but I have read this can be achieved by simply referencing this in the field you want to reference the current model.
The model you would like to will look something like this,
const mongoose = require('mongoose')
const FolderSchema = mongoose.Schema({
name: { type: String, required: true },
type: { type: String, enum: ['file', 'directory'],
children: [ this ]
})
const FolderModel = mongoose.model('Folder', FolderSchema);
Hope that helps!
look you need to clarify your question a little bit but as much as i understood from the question, yes it can be done in this way :
var mongoose = require('mongoose');
var FolderSchema = new mongoose.Schema({
SubFolders = [ type:monogoose.Schema.Types.ObjectId, ref : 'Folders']
});
var folder = mongoose.model('Folders',FolderSchema);
module.exports = folder;
This shall work for you.
So for infinite object having children, I did it like so:
mongoose schema:
const itemSchema = new mongoose.Schema({
name: String,
items: {
type: [this],
default: undefined
}
}, { _id: false })
const mainSchema = new mongoose.Schema({
name: String,
items: {
type: [itemSchema],
default: undefined
}
})
output example:
[
{
_id: '62a72d6915ad7f79d738e465',
name: 'item1',
items: [
{
name: 'item1-item1',
items: [
{
name: 'item1-item1-item1'
},
{
name: 'item1-item1-item2'
},
{
name: 'item1-item1-item3'
},
]
},
{
name: 'item1-item2'
}
]
},
{
_id: '62a72d6915ad7f79d738e467',
name: 'item2'
},
{
_id: '62a72d6915ad7f79d738e467',
name: 'item3',
items: [
{
name: 'item3-item1'
}
]
}
]