Mongoose .find() with conditions returns no result - node.js

I am working on a MEAN Stack app with a pre-existing MongoDB collection and if I define conditions for .find() no results were returned while it works without conditions.
Here is the code from my model file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mainSchema = new Schema({
id: Number,
x: Number,
y: Number,
prio: Number,
type0: String,
type1: String,
type2: String,
width: Number,
height: Number,
text1: String,
text2: String,
size1: Number,
font: String,
color1: String,
color2: String,
links: String,
peers: String
}, { collection: 'main' });
mainSchema.statics = {
load: function(l, t, r, b, cb){
console.log(l, t, r, b);
return this.find({
x: { $gt: l, $lt: r },
y: { $gt: t, $lt: b }
}).exec(cb);
}
};
module.exports = mongoose.model('main', mainSchema);
This is one object from the output without conditions:
[
{
"_id": "577faf952a7c33f2fe44b282",
"id": 4,
"x": 50944,
"y": 54995,
"prio": 1,
"type0": "a",
"type1": "a",
"type2": "a",
"width": 100,
"height": 100,
"text1": "Chemie",
"text2": "",
"size1": 48,
"font": "f1_a ",
"color1": "#000000",
"color2": "#bfdeff",
"links": "14,53445,57328,12,#ff3d3d,k&13,54744,53904,12,#8c8c86,k&12,52557,51870,12,#f2ff12,k&11,51172,49743,12,#2312ff,k&10,48270,47335,12,#49fe6e,k&",
"peers": "1"
}
]
Here is the code that calls the load methode:
var mongoose = require('mongoose');
var main = require('../models/main');
exports.load = function(req, res){
main.load(parseInt(req.query.l), parseInt(req.query.t), parseInt(req.query.r), parseInt(req.query.b), function(err, data) {
res.jsonp(data);
});
};

Problem solved!
Despite the output all data were stored as strings instead of int within MongoDB.
I just copied the JSON output (where the types are correct) to a file and imported it to MongoDB, now the code works fine.

Related

How to post multiple array Nodejs

I need to post multiple array at the same time so i can achieve this :
{
name:"John Snow",
detail: [
{size: "M", total: 5, color: "red"},
{size: "S", total: 2, color: "black"}
]
}
i'm using dynamic form that can generate new input field for detail array. so this is my schema model :
const OrderSchema = new Schema({
name:{
type: String,
required: true
},
detail:[{
size:{},
color:{},
total:{}
}],
date:{
type: Date,
default: Date.now
}
});
this is my route post :
router.post('/add', (req, res) => {
let errors = [];
if (!req.body.name) {
errors.push({ text: 'Your customer name is empty' });
}
if (errors.length > 0) {
res.render('orders/add', {
errors: errors,
customer: req.body.name,
detail:[{
size: req.body.size,
color: req.body.color,
total: req.body.total
}]
});
} else {
const newUser = {
customer: req.body.name,
detail:[{
size: req.body.size,
color: req.body.color,
total: req.body.total
}
new Order(newUser)
.save()
.then(order => {
res.redirect('/');
})
}
});
submit post is work, it just the result is not what i want :
{
name:"John Snow",
detail: [
{size: ["M","S"], total: [5,2], color: ["red", "black"]}
]
}
i hope you can help me, thanks!
Let's assume you have your details in a request body.
The req.body.details would look like this:
details: [
{size: "M", total: 5, color: "red"},
{size: "S", total: 2, color: "black"}
]
You could then simply save it altogether like so:
detail: req.body.details
Note that your Schema for details is a bit odd:
detail:[{
size:{}, // seems to be a string not an object
color:{}, // seems to be a string not an object
total:{} // seems to be a number not an object
}]
Instead, I think you could do:
detail:[{
size:{type: String},
color:{type: String},
total:{type: Number}
}]
Edit:
Since you do not seem to validate the details, you could simply make it an array in your Schema (that is up to you and what works best).
detail: { type: Array }
In general req.body.details could come from wherever you make the request. It could be sorted and equal to the array that you want to save in the database.
I am not fully aware of what is in your req.body.size for example but if it is an array such as ["M","S"] then you would extract each element and create separate objects that you would then push to the array which you would be saving in your database.
Have a look below:
let size = ["M","S"]
let total = [5,2]
let color = ["red", "black"]
let detailsToDb = []
for (let i=0; i<size.length; i++) {
detailsToDb.push({
size: size[i],
color: color[i],
total: total[i]
})
}
console.log(detailsToDb)
In your case you could use req.body.size[i] etc. right away, no need to initialize the variables.
let detailsToDb = []
for (let i=0; i<req.body.size.length; i++) {
detailsToDb.push({
size: req.body.size[i],
color: req.body.color[i],
total: req.body.total[i]
})
}

Getting error during the time of inserting the query on database

I am Facing the error at the time of insert the query.
Error is "db.collection.insert is not a function"
My database schema is like this
'use strict';
var mongoose = require('mongoose');
//Schema
var ABCSchema = mongoose.Schema({
sequenceid: {
type: Number
},
A: {
type: Array,
default: []
},
B: {
type: Array,
default: []
},
C: {
type: Array,
default: []
},
D: {
type: Array,
default: []
}
});
var ABC = module.exports = mongoose.model('ABC', ABCSchema);
Now I want to enter the data which looks like this.
It's just a sample by which you people can understand that how I can Store the value.
{
"_id" : ObjectId("5a2e2eb9104cce1b58385620"),
"sequenceid": 1,
"A" : [
{
"apple" : "red",
"count" : 24
}
],
"B" : [],
"C" : [],
"D" : [],
"__v" : 0
}
Now what I am trying to code is like this
ABC.insert({'sequenceid': 1, 'A': {'apple': 'red', 'count': 24}}, function(error, data){
console.log(data);
});
As #Manjeet Thakur pointed out what you are trying to insert at "A" is and object and not an Array
Change it to array
{
"A": [{
"apple": "red",
"count": 24
}],
"sequenceid": 1
}
Also you need to instantiate your model and save it
var abc = new ABC({'sequenceid': 1, 'A': [{'apple': 'red', 'count': 24}]});
abc.save()
//or
ABC.create({'sequenceid': 1, 'A': [{'apple': 'red', 'count': 24}]}, function (err, small) {
//if (err) return throw err;
// saved!
})
'use strict';
var mongoose = require('mongoose');
//Schema
var ABCSchema = mongoose.Schema({
sequenceid: {
type: Number
},
A: {
type: Array,
default: []
},
B: {
type: Array,
default: []
},
C: {
type: Array,
default: []
},
D: {
type: Array,
default: []
}
});
var ABC = module.exports = mongoose.model('ABC', ABCSchema);
// here now collection is ABC (name of collection)
ABC.insert({'sequenceid': 1, 'A': [{'apple': 'red', 'count': 24}] }, function(error, data){
console.log(data);
});

How two select two column value as key value pair in mongoose using expressjs

i have the schema is like below
Resource.js
var mongoose = require("mongoose"),
Schema = mongoose.Schema,
objectId = mongoose.Schema.ObjectId;
var lableShema = new Schema({
labelName: { type: String },
language: { type: String, },
resourceKey: { type: String, },
resourceValue: { type: String, }
}, {
versionKey: false
});
var lableShema = mongoose.model('LabelKeyResource', lableShema);
module.exports = lableShema;
in db i have the data like this,
{
"_id": "59b1270b4bb15e1358e47cbd",
"labelName": "submit",
"__v": 0,
"resourceKey": "submit_btn",
"resourceValue": "Submit",
"language": "engilish"
}
i'm using the select function is
lableResource.find({ language: req.params.ln}, function (err, data) {
if (err) {
res.send(err);
return;
}
res.send(data);
but i want this format how to that...
{"submit_btn":"Submit","select_lbl":"Please Select"}
You can format the data after getting the data from Mongo.
This is how you can do it:
var obj = {
[data.resourceKey]: data.resourceValue,
select_label: "Please Select"
};
This will give you the object: {"submit_btn":"Submit","select_lbl":"Please Select"}

MongoDB returning empty array

I'm trying to populate albums with images using userid sent through params but i end up with an empty array even though there is data in database.
"use strict"
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema
console.log('Welcome');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
mongoose.connect('mongodb://localhost/Datab');
var db = mongoose.connection;
db.once('open', function () {
console.log('Connected to Database');
});
//Schema for the data
var userSchema = new mongoose.Schema({
name: String
});
var albumSchema = new mongoose.Schema({
userid: String,
albumName: String,
albumDesc: String,
albumThumbnail: String,
imageCount: Number,
images: [{
type: Schema.Types.ObjectId,
ref: 'Image'
}]
});
var ImageSchema = new Schema({
album_id: {
type: String,
ref: 'Album'
},
imageName: String,
imageDescription: String,
imageURL: String,
likeCount: Number,
commentCount: Number
})
var Userdata = mongoose.model('Userdata', userSchema);
var Album = mongoose.model('Album', albumSchema);
var Image = mongoose.model('Image', ImageSchema);
//display of albums
app.get('/user/:user_id/photos', function (req, res) {
var user_id = req.params.user_id
Album.find({
userid: user_id
})
.populate('images')
.exec(function (err, albums) {
if (!err) {
return res.send({
status: {
error: 0,
message: "Successful"
},
data: {
albums: albums
}
})
} else
res.send('Unsuccessful');
})
});
app.listen(3000);
output:
{
"status": {
"error": 0,
"message": "Successful"
},
"data": {
"albums": []
}
}
why do i get an empty array as output?
Find in the mongo shell returns the following result
db.Album.find() {
"_id": ObjectId("529eed506c7b0a09b2204203"),
"albumDesc": "outings",
"albumName": "Photoclics1",
"albumThumbnail": "http: //192.168.71.250/uploads/cat1_thumb.jpg",
"imageCount": "1",
"images": ["529ef0016c7b0a09b2204205", "529ef0266c7b0a09b2204206"],
"userid": "529eec5a6c7b0a09b22041ff"
}
EDIT 2: This is the output that i expect to get
{
"error": {
"status": 0,
"message": "Successful"
},
"data": {
"albums": [
{
"albumName": "myclicks",
"albumID": "527102fdaed86d8807000001",
"albumDescription": "PhotosIclicked",
"albumThumbnailURL": "http: //192.168.71.250/uploads/image.jpg",
"imageCount": 2,
"images": [
{
"imageID": "527102fdaed86d8807000001",
"imageName": "mycat",
"imageDescription": "billy",
"imageURL": "http: //192.168.71.250/uploads/cat.jpg",
"imageThumbnailURL": "http: //192.168.71.250/uploads/cat_thumb.jpg",
"likeCount": 21,
"commentCount": 1
},
{
"imageID": "527102fdaed86d8807000001",
"imageName": "mycat",
"imageDescription": "billy",
"imageURL": "http: //192.168.71.250/uploads/cat1.jpg",
"imageThumbnailURL": "http: //192.168.71.250/uploads/cat1_thumb.jpg",
"likeCount": 21,
"commentCount": 1
}
]
}
]
}
The identifier stored in the images array is shown as a String in the console. Yet, the definition in the schema for the images field is shown as the type ObjectId. If you either fix the data to be an ObjectId or change the data type, the issue should be resolved.
You could fix the data in the MongoDB console by iterating through the collection and the array and converting each element to an ObjectId.

Mongoose query doesn't work with where() when filtering by numeric values

So I am having trouble with queries using mongoose when using the where clause. They work when I filter on strings, but not with numbers.
Here is my model/schema:
// Schema
var Wheel = new mongoose.Schema({
name: String,
method: String,
size: Number,
width: Number,
weight: Number
});
// Model
var WheelModel = mongoose.model('Wheel', Wheel);
This query works:
var query = WheelModel.find();
query.where('method').equals('Cast/Spun');
query.limit(10);
query.exec(function (err, wheels) {
// wheel objects are returned
});
This is an example of a wheel object inside the array 'wheels'
{
"_id": "523de98b263add11a8d4fc4a",
"name": "AME Circlar RS",
"weight": 18.1,
"width": 7,
"method": "Cast/Spun",
"size": 15
}
This query below returns [], and does so for if I filter by size, width, and weight, and for any numbers
var query = WheelModel.find();
query.where('size').equals(15);
query.limit(10);
query.exec(function (err, wheels) {
if (!err) {
return res.send(wheels);
} else {
return console.log(err);
}
});
I have also tried
query.where('size', 15);
query.where('size', '15');
var query = WheelModel.find({ size: 15});
If I go:
query.where('size').ne(15);
Then I get results back, but they will include values where the size is 15. So I suspect I have some type issues, I just don't know what. Any help would be apprecicated!
Try the following schema it should work for you (as per understanding from your comments) with the same query i.e. query.where('size').equals(15)
var Wheel = new mongoose.Schema({
name: String,
method: String,
size: { type: Number },
width: { type: Number},
weight: { type: Number }
});
For more information, check this Schema Types in API docs.

Resources