I want to populate the category field in product schema.
The code for my product schema is
const mongoose = require('mongoose');
const {ObjectId} = mongoose.Schema
const productSchema = new mongoose.Schema({
name :{
type:String,
required : true,
trim : true,
maxlength : 32,
},
description : {
type:String,
required : true,
trim : true,
maxlength : 2000,
},
price : {
type : Number,
required : true,
maxlength :32
},
category : {
type : ObjectId,
ref : "Category",
required : true
},
stock : {
type : Number,
},
sold : {
type :Number,
default : 0
},
photo : {
data : Buffer,
contentType : String
}
},{timestamps:true})
module.exports = mongoose.model("Product",productSchema);
And The code which i am using to populate the category field is
exports.getAllProducts = (req,res)=>{
let no_of_products = req.query.limit? parseInt(req.query.limit):8;
let sortBy = req.query.sortBy?req.query.sortBy : "price"
Product.find()
.populate("catgeory")
.select("-photo")
.sort({sortBy:1})
.limit(no_of_products)
.exec((err,products)=>{
if(err){
console.log(err);
return res.status(400).json({
error : "some error occured"
})
}
})
}
But this code is giving me error which say
cannot populate path Catgeory because it is not in your schema. Set the strictPopulate option to false to override.
I have read documentation but i am unable to alter my code . Kindly help me with this issue.
check the Product databases table that you have category keys and you should know that the object Id is correct and it comes from the category table if not you should drop the database or drop the product collection and create the new one
Related
I want to save the large html content in mongodb but it doesn't allow to save more than 1 kb of content in single field of collection.
Basically i am building a article submission web app using NUXT & database i choose is Mongodb. Now i am stuck in this crucial task.
any help would be great!
var mongoose = require('mongoose');
var ArticleSchema = new mongoose.Schema({
title : { type : String , unique : true, required : true},
description: { type : String , unique : true, required : true},
content: { type : String , unique : true, required : true},
banner: { type : String },
active: { type: Boolean, default: false },
created_date: { type: Date, default: Date.now },
updated_date: { type: Date, default: Date.now },
postedBy: {
type : Object , required : true
},
comments: [{
text: String,
postedBy: {
type : Object , required : true
}
}]
});
module.exports = mongoose.model('Article', ArticleSchema);
Getting this error while saving large content:
Btree::insert: key too large to index, failing tech-expert.articles.$content_1 3500 { : \"<p>Here is Sample text!Here is Sample text!Here is Sample text!Here is Sample text!Here is Sample text!Here is Sample text!Here is Sample text!Here is...\" }"}
Seems like you have an index on content field. Consider removing this index, or replacing it with text index
UPD: Mongoose would automatically create Unique index if you schema says unique: true - just get rid of this part for the content field. Mongoose Schema Type
I've got an Express application which until this morning was returning an array of objects from the database. Now it's returning an empty array. RoboMongo shows me that the data is still there and doing fine. Any ideas?
My model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const plotStatusSchema = new Schema(
{
recordDate: Date,
blockName: String,
growerName: String,
company: String,
variety: String,
planted: Number,
region: String,
yieldInKG: Number,
changeInPcnt: Number,
currentRipeness: String,
nextStage: String,
timeToNextInDays: Number,
status: Number
},
{ bufferCommands: false },
{ collection: 'plotStatuses' }
);
const ModelClass = mongoose.model(
'plotStatus',
plotStatusSchema,
'plotStatuses'
);
module.exports = ModelClass;
My returning controller:
const PlotStatus = require('../models/plotStatus');
const jsonpack = require('jsonpack');
exports.plotStatuses = async (req, res) => {
const plotStatus = await PlotStatus.find({
company: 'req.user.companyCode'
}).lean();
if (!plotStatus) {
throw new Error('Plot Statuses not found');
} else {
res.send(plotStatus);
}
};
A sample of my data:
{
"_id" : ObjectId,
"recordDate" : ISODate,
"blockName" : String,
"blockCode" : String,
"growerName" : String,
"company" : String,
"variety" : String,
"planted" : ISODate,
"region" : String,
"yieldInKG" : Number,
"changeInPcnt" : Number,
"currentRipeness" : String,
"nextStage" :String,
"timeToNextInDays" : Number,
"status" : Number,
"targetYieldInKG" : Number,
"currentStatePercentage" : Number,
"totalLengthOfPhase" : Number,
"nextPhaseStart" : ISODate,
"currentBrix" : Number,
"currentPh" : Number,
"currentTA" : Number,
"plotGeoJSON" : Object,
"historicalData" : Array
}
I know that the Schema no longer matches the shape of the JSON, but can I return all the JSONs that fit the find condition anyway?
You are searching the string "req.user.companyCode" inside the company attribute. Obviously, you don't have that company code in your data. Try it again without the quores:
const plotStatus = await PlotStatus.find({
company: req.user.companyCode
}).lean();
I'm using Express to do a find operation in a Mongo collection and return the result. I know that there is data in the collection, but the result array comes back empty. I suspect that it's an issue with the schema, but can't figure out what. Thoughts?
Route:
const PlotStatus = require('../models/plotStatus');
exports.plotStatuses = async (req, res) => {
const plotStatus = await PlotStatus.find({
company: req.user.companyCode
}).lean();
if (!plotStatus) {
throw new Error('Plot Statuses not found');
} else {
res.send(plotStatus);
}
};
Model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const plotStatusSchema = new Schema(
{
recordDate: Date,
blockName: String,
growerName: String,
company: String,
variety: String,
planted: Number,
region: String,
yieldInKG: Number,
currentRipeness: String,
nextStage: String,
timeToNextInDays: Number,
status: Number
},
{ bufferCommands: false },
{ collection: 'plotStatuses' }
);
const ModelClass = mongoose.model('plotStatus', plotStatusSchema);
module.exports = ModelClass;
Sample plotStatus:
{
"_id" : ObjectId("stringhere"),
"recordDate" : ISODate("2018-01-02T12:50:51.236Z"),
"blockName" : "name",
"growerName" : "grower's name",
"company" : "mycompany",
"variety" : "myvariety",
"planted" : 2010,
"region" : "myregion",
"yieldInKG" : 960,
"changeInPcnt" : -1.6,
"currentRipeness" : "ripeness",
"nextStage" : "nextstage",
"timeToNextInDays" : 42,
"status" : 0
}
Okay, got it.
Typically, Mongoose infers the collection name from the model name, but you can pass it explicitly. Apparently, plotStatus => plotStatuses was a bridge too far. This fixed it:
const ModelClass = mongoose.model(
'plotStatus',
plotStatusSchema,
'plotStatuses'
);
I need to save or insert a new record into my mongo database. I hope the field "userid" of it can automatically increase by 1. Is it possible to do it in mongodb?
Schema
generalUserApplication: {
userid: Number, // 1
lora: [
{},
{}
]
}
Here's the way from the mongo tutorial.
You need to create new collection counters in your db.
function getNextSequence(db, name, callback) {
db.collection("counters").findAndModify( { _id: name }, null, { $inc: { seq: 1 } }, function(err, result){
if(err) callback(err, result);
callback(err, result.value.seq);
} );
}
Then, you can use getNextSequence() as following, when you insert a new row.
getNextSequence(db, "user_id", function(err, result){
if(!err){
db.collection('users').insert({
"_id": result,
// ...
});
}
});
I have use another package named 'mongoose-sequence-plugin' to generate sequence which is auto-incremented by 1.
Here I am posting code that I have tried for same problem. Hope it will help.
Schema :
var mongoose = require('mongoose');
var sequenceGenerator = require('mongoose-sequence-plugin');
var Schema = mongoose.Schema;
var ProjectSchema = new Schema({
Name : { type : String, required: true },
Description : { type : String, required: true },
DetailAddress : { type : String, required: true },
ShortAddress : { type : String, required: true },
Latitude : { type : Number, required: true },
Longitude : { type : Number, required: true },
PriceMin : { type : Number, required: true, index : true },
PriceMax : { type : Number, required: true, index: true },
Area : { type : Number, required: true },
City : { type : String, required: true }
});
ProjectSchema.plugin(sequenceGenerator, {
field: 'project_id',
startAt: '10000001',
prefix: 'PROJ',
maxSaveRetries: 2
});
module.exports = mongoose.model('Project', ProjectSchema);
This will create projects collection with parameter project_id starting from PROJ10000001 and on wards. If you delete last inserted record then this package reads the current last entry of field project_id and next id is assigned by incrementing current id.
I've written the following MongooseJS schema.The field "likers" is an embedded record which currently is a POJO with two keys. Can the embedded schema be a hash map with each "liker" field serving as the key?
Here's what the hash map should look like :
const userlikers = {
{'100900800' : 'user'}
{'100989455' : 'user'}
{'109099985' : 'user'}
}
Here's the current schema
const userlikers = Schema({
users : {
type: Schema.Types.Mixed
}
})
const PicSchema = Schema ({
url : {
type : String,
required : true
},
desc : {
type : String,
required : true
},
likers : [userlikers],
created : {
by : {
type : Schema.Types.ObjectId,
ref : 'User',
required : true
},
at : {
type : Date,
default : Date.now
}
}
})
const Pic = mongoose.model('Pic', PicSchema);
module.exports = Pic;
I know it is so late,
From mongoose version 5.10.9 you can use the map instead of type: Schema.Types.Mixed
const PicSchema = Schema ({
..............
........
likers : {
type: Map,
of: String
},
........
........
})