Mongoose - Query returns nothing - node.js

I have the following query:
app.get('/matches/:latMin/:latMax/:lonMin/:lonMax', function(req, res){
var matches = City.find({
"latitude": {$gt : String(req.param.latMin), $lt : String(req.params.latMax) },
"longitude" : {$gt : String(req.param.lonMin), $lt : String(req.param.lonMax)}
});
matches.exec(function(err, match){
if(err){
console.log(err);
return res.send(err);
}
console.log(match);
res.json(match);
});
});
Here is my schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('City', new Schema({
zip : {type : String, default: ''},
latitude : {type : String, default: ''},
longitude : {type: String, default: ''},
city : {type: String, default: ''},
state : {type: String, default: ''},
county : {type: String, default: ''}
}), 'locations');
When I run the query in the Mongo shell, the expected results are sent. However, the log in the above quotes returns []. Is there something wrong I'm doing here?

I don't know if you want to use req.param or it is just a typo. Anyway, req.param is deprecated and you should use req.params.
I have set up your scenario and queries are working. Replace the var matches in your code for the following:
var matches = City.find({
"latitude": {$gt : String(req.params.latMin), $lt : String(req.params.latMax) },
"longitude" : {$gt : String(req.params.lonMin), $lt : String(req.params.lonMax)}
});

Related

node js mongoose find inside nested mixed property?

I have a mongoose schema like this.
var schema = new mongoose.Schema({
t: {type: Date, required: true},
o: {type: String, required: true},
d: {type: mongoose.Schema.Types.Mixed, required: true}
}
the objects in mongoDb are like this.
{
"_id" : ObjectId("5d36948b7f40460dd0d28934"),
"t" : ISODate("2019-07-23T05:00:59.518Z"),
"o" : "u",
"d" : {
"room" : "5c0508cd12e0fc3310a8ba00",
"noOfTimesSwapped" : 4,
"modifiedAt" : "2019-07-23T05:00:59.517Z",
"modifiedBy" : "5c73d5f2e4c2754e0cd5246a",
"p" : {
"_id" : "5d35bac67660ad2dd8fbb57d"
}
}
}
I want to get the records which matches with the _id of the 'p' field which is a property of d.
I have tried to get records using the following criteria, but that does not work.
MyModel.find({ 'd.p._id': id }, function (err, docs) {});

Mongoose- How to use discriminators in subdocument

I want the output to be like this
var FeedSchema = new Schema({
timestamp : {type : String, required : true},
feed_type_code : {type : Number, required : true},
gender : {type : String, required : true},
feed_item : Article || Tip || etc.
}
Hence, I understand I have to use discriminators. I followed the following SO answer
Here is what I did:
var feed_type = {discriminatorKey : 'feed_item'};
var FeedSchema = new Schema({
timestamp : {type : String, required : true},
feed_type_code : {type : Number, required : true},
gender : {type : String, required : true}
}, feed_type);
var TipSchema = new Schema({
tip : {type : String, required : true},
subtip : {type : String, required : true},
display_count : {type : Number},
likes : {type : Number}
}, feed_type);
var ArticleSchema = new Schema({
title : {type : String, required : true},
english_title : {type : String, required : true},
image_url : {type : String, required : true},
article_text : {type : String, required : true},
english_article_text : {type : String},
author : {type : String},
english_author : {type : String}
}, feed_type);
Here is how I am saving the document:
var article = new Article({
title : req.body.title,
english_title : req.body.english_title,
image_url : req.body.image_url,
article_text : req.body.article_text,
english_article_text : req.body.english_article_text,
author : req.body.author,
english_author : req.body.english_author
});
var feed = new Feed({
gender : req.body.gender,
timestamp : moment().valueOf(),
feed_type_code : 9002,
feed_item : article
});
feed.save(function(err, doc){
if(err){
res.json({success : -1});
return;
}
res.json({success : 1, feed : doc});
});
I am not getting the article output for this:
{
"success": 1,
"feed": {
"__v": 0,
"gender": "female",
"timestamp": "1481460218959",
"feed_type_code": 9002,
"_id": "584d49faa6ff3a23bc868ab3"
}
}
I am new to Nodejs. I would appreciate if you can point out the error.
in the model file add these lines
var Feed = mongoose.model('Feed', FeedSchema, 'feed');
var Article = Feed.discriminator('Article', ArticleSchema);
var Tip = Feed.discriminator('Tip', TipSchema);
module.exports = {
Feed : Feed,
Article : Article,
Tip : Tip
}
This is how you save the document. You don't need to create a separate Feed object.
var article = new Article({
gender : req.body.gender,
timestamp : moment().valueOf(),
feed_type_code : 9002,
title : req.body.title,
english_title : req.body.english_title,
image_url : req.body.image_url,
article_text : req.body.article_text,
english_article_text : req.body.english_article_text,
author : req.body.author,
english_author : req.body.english_author
});
article.save(function(err, doc){
if(err){
console.log(err);
res.json({success : -1});
return;
}
res.json({success : 1, feed : doc});
});

Mongoose doesn't create model object with array

I'm working on a project where I have the following mongoose schema:
module.exports = mongoose.model('Env', {
name : {type : String, default: ''},
services: [ServiceAddress]
});
module.exports = mongoose.model('ServiceAddress', {
serviceId : {type : ObjectId},
address: {type: String}
});
I'm trying to update an existing 'Env' document which has an empty array of 'services'.
router.put('/api/env', function(req, res, next) {
var env = new Environment(req.body);
env.save(function(err, updated){
if (err){
res.send(err);
}
res.json(updated);
});
});
The req.body content is:
{
_id: "56dd26a6618c1b983d5bada6",
name: "Test Drive"
services: [{_id: "56dc6e385fb0b038241d3399", address: "11"}, {_id: "56dc6e595fb0b038241d339a", address: ""}]
}
But the result in the DB is (only the IDs are pushed):
"services" : [ { "_id" : ObjectId("56dc6e385fb0b038241d3399") }, { "_id" : ObjectId("56dc6e595fb0b038241d339a") }
Any idea?
Thanks
Please try out with following snippet
var serviceSchema = {
serviceId : {type : ObjectId,required: false},
address: {type: String,required: false}
};
// added so that new _id field is not added when object is pushed in array
serviceSchema = 'new Schema('+serviceSchema +',{_id:false})';
module.exports = mongoose.model('Env', {
name : {type : String, default: ''},
services: [serviceSchema], default:[],
});
Thanks

Node.js - Create Relationships with Mongoose from different file

I have two Schemas Products and Users in different files. Products are belong to User and User have many Product
The Problem is, I have try to use Populate but somehow it return not what I expected.
here is my Schema for Product on models products.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var users = require('../models/users');
var Product = mongoose.Schema({
user_id : {type: String, required: true },
category_id : {type: String, default: null},
title : {type: String, required: true },
content : {type: String, default : "" },
pictureUrls : Array,
counter : {type : Number, default : 0},,
lowercaseTitle : {type: String, default : null },
_user : { type: Schema.Types.ObjectId, ref: users.User }
});
Product.set('toObject', {
getters: true,
virtuals: true
});
module.exports = mongoose.model('Product', Product)
and this is my Schema for User on models users.js
var mongoose = require('mongoose');
var User = mongoose.Schema({
firstName : {type: String, default: "" },
lastName : {type: String, default: "" },
username : {type: String, required: true },
email : {type: String, required: true },
password : {type: String, default: "" },
bio : {type: String, default: "" },
website : {type: String, default: "" },
phone : {type: String, default: "" },
gender : {type: String, default: "" },
birthDate : {type: Date, default: null },
avatarUrl : {type: String, default: "" },
verified : {type : Boolean, default : false}
});
User.set('toObject', {
getters: true,
virtuals: true
});
module.exports = mongoose.model('User', User);
currently I am using method find by calling each Models
User.findOne({"sessionToken" : bearerHeader}, function (err, user){
Product.find({"user_id" : user._id}, function (err, products){
console.log(products);
});
});
but it takes time and became problem if there related to another models.
I'm calling populte with this
Product.findOne({}).populate('_user').exec(function(err, p){
console.log(p);
});
but attribute _user was not set and undefined
any help?
Thanks

update object inside array that is inside collection

I need to update field "rightAnswer" in object inside array that is inside collection.
How can I change boolean of specific comment to true for right question.
In Angular I pass id of question and id of comment to backend. But on the backend I don't know how to update that field. I use MEAN stack.
Question schema:
var questionSchema = new mongoose.Schema({
title: {type : String, default : '', trim : true},
text: {type : String, default : '', trim : true},
publisher_id: {type : mongoose.Schema.ObjectId, ref : 'User'},
answers: [{
body: { type : String, default : '' },
user: { type : mongoose.Schema.ObjectId, ref : 'User' },
rightAnswer: { type : Boolean, default: false },
createdAt: { type : Date, default : Date.now }
}],
date : {type : Date, default : Date.now}
});
My route in express:
Question.update({_id: req.body.question._id}, {"answers._id": req.body.answer._id}, {$set: {"answers.$.rightAnswer": true} }, function(req, data){
res.json(data);
});
Solution:
Question.update({_id: req.body.question._id,
"answers": {$elemMatch: {_id: req.body.answer._id}}},
{$set: {"answers.$.rightAnswer": true}},
function(req, res){});
Question.update({_id: req.body.question._id,
"answers": {$elemMatch: {_id: req.body.answer._id}}},
{$set: {"answers.$.rightAnswer": true}},
function(req, res){});

Resources