I am trying to get all documents in mongo collection but instead i am getting empty response. my database name is taskDb which has a collection named item in which all the documents are stored. I think maybe there is some problem with schema but mongo is schema less db so i am not able to find the solution.
index.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
Items = require('./items.js');
mongoose.connect('mongodb://localhost/taskDb');
var db = mongoose.connection;
app.get("/",(req, res)=> {
res.send('Visit /api/*****');
});
app.get("/api/items",(req, res)=> {
Items.getItems(function(err, items){
if(err){
throw err;
}
console.log(res.json(items));
res.json(items);
});
});
// app.get("/api/matches",(req, res)=> {
// Matches.getMatches(function(err, matches){
// if(err){
// throw err;
// }
// res.json(matches);
// });
// });
// app.get("/api/deliveries/:playerName",(req, res)=> {
// Deliveries.getPlayerStats(req.params.playerName ,function(err, deliveries){
// if(err){
// throw err;
// }
// res.json(deliveries);
// });
// });
app.listen(3005,()=>{
console.log('Listening on port 3005...');
});
item.js
var mongoose = require('mongoose');
var itemSchema = mongoose.Schema({
_ID:{
type: String,
required: true
},
ITEM:{
type: String,
required: true
},
KEY:{
type: Number,
required: true
},
STATUS:{
type: String,
required: true
}
});
var Item = module.exports = mongoose.model('item', itemSchema);
// module.exports.getPlayerStats = function (playerName, callback) {
// Deliveries.aggregate([{$project:{_id: 1,batsman: 1 ,batsman_runs: 1, dismissal:{
// $cond: [ { $eq: ["$player_dismissed", playerName ] }, 1, 0]
// }}},{ $match: { batsman: playerName } },
// { $group: {_id: "$batsman", total_runs: { $sum: "$batsman_runs" },total_dismissal: { $sum: "$dismissal"}}}
// ], callback);
// }
module.exports.getItems = function (callback, limit) {
Item.find(callback).limit(limit);
};
There are two issues I see in getItems function:
Condition for find() is not specified. In case you want to read all records, you can specify it as empty object.
Limit parameter is not being passed from your request handler to getItems function. You would either need to default it to some number or handle the scenario where limit won't be passed.
Modifying getItems() to something like below should work:
module.exports.getItems = function (callback, limit) {
Item.find({}, callback).limit(limit || 20); // Default limit to a feasible number
};
Also, you can pass limit to getItems() function from request handler if you want to override default:
app.get("/api/items",(req, res)=> {
Items.getItems(function(err, items){
if(err){
throw err;
}
console.log(res.json(items));
return res.json(items);
}, 50); // Pass limit
});
Related
Here's my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostsSchema = new Schema({
userId: String,
postId: String,
title: String,
description: String,
tags: { many: String, where: String, what: String },
date: { type: Date, default: Date.now },
}, { collection : 'posts'});
const Posts = mongoose.model('Post', PostsSchema);
module.exports = Posts;
Here's my route with the query:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Posts = require('../models/Posts');
router.get('/', (req, res, next) => {
const refreshOrLoadMore = params.refreshOrLoadMore || '';
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10, (err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}
});
The if statement returns true and the first console.log is triggered. But after that none of the other console.logs are triggered and just nothing happens. No data is being send and no error is being send.
So my guess is, that i did something wrong with the Schema, but i did it just as i did my other ones and they do work.
Can someone point out where i went wrong?
Thanks in advance!
Try this
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10)
.exec((err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}
// Models
var mongoose = require('mongoose');
var ProfileSchema = new mongoose.Schema({
fullName: {
type: String,
required: true
}
// profileImage: {type: String, required: true}
});
module.exports = mongoose.model('Profile', ProfileSchema)
// Controllers
var Profile = require('../models/profile');
var multer = require('multer');
var upload = multer({dest: 'uploads/'});
exports.createProfile = (upload.single('profileImage'), function (req, res, next) {
var profileData = {
fullName: req.body.fullName,
// profileImage: req.file
}
console.log(req.file);
console.log('req.file: ', JSON.stringify(req.file));
console.log(profileData);
Profile.create(profileData, function (err, profile) {
if (err) {
// console.log(err);
res.end();
return;
// res.send(err);
}
Profile.create(function (err, profiles) {
if (err) {
res.end();
// res.send(err);
return;
}
res.json(profileData);
});
});
});
I'm trying to use middleware to add text and image at the same time in the MongoDB database. However, my fields aren't populated and when I try to print it out in the console it says req.file(): undefined. I've researched on the other issues and it states using 'upload.single()' will solve the problem. In my case, it didn't! The first section is my model view(Schema), the second section is my controllers' view.
I have a node.js project and I need to get 8 random documents which are not sequential from my mongoDB database using Mongoose.
My Schema:
var mongoose = require('mongoose');
var random = require('mongoose-simple-random');
var schema = new mongoose.Schema({
title: String,
width:String,
height:String,
});
var Images = mongoose.model('Images', schema);
Images.count().exec(function (err, count) {
// Get a random entry
var random = Math.floor(Math.random() * count)
// Again query all users but only fetch one offset by our random #
Images.find({}).limit(8).skip(random).exec(
function (err, result) {
// Tada! random user
console.log(result)
//res.send(results);
})
})
module.exports = {
Images: Images
};
When calling the function in my route file (Main.js):
var Images = require('../models/images.js');
app.get('/homepage', function(req, res){
var rand = Math.floor(Math.random() * 10000);
Images.find({}).limit(8).skip(rand).exec(function(err, docs){
res.render('homepage', {images: docs});
});
});
How would I call the 'find' function in my model from my main.js route file?
You could use the following to get unique items with $sample but grouping by _id to remove possible duplicates in the random result :
db.images.aggregate([{
$sample: { size: 100 }
}, {
$group: {
_id: "$_id",
document: { $push: "$$ROOT" }
}
}, {
$limit: itemCount
}, {
$unwind: "$document"
}])
For the structure of your code, you could define a static method getRandomItems, storing your mongoose object in express app.db and calling the mongoose object from your router with req.app.db :
model.js
'use strict';
exports = module.exports = function(app, mongoose) {
var schema = new mongoose.Schema({
title: String,
width: String,
height: String,
});
schema.statics.getRandomItems = function(itemCount, cb) {
this.aggregate([{
$sample: { size: 100 }
}, {
$group: {
_id: "$_id",
document: { $push: "$$ROOT" }
}
}, {
$limit: itemCount
}, {
$unwind: "$document"
}], cb);
};
app.db.model('Images', schema);
};
app.js
'use strict';
var mongoose = require('mongoose'),
express = require('express');
var app = express();
app.db = mongoose.createConnection("mongodb://localhost/testDB");
// config data models
require('./models')(app, mongoose);
require('./routes')(app);
app.listen(8080, function() {
});
routes.js
'use strict';
exports = module.exports = function(app) {
// BboxAPI
app.get("/random", function(req, res) {
req.app.db.models.Images.getRandomItems(8, function(err, result) {
if (err) {
console.log(err);
res.status(500).json(err);
} else {
res.status(200).json(result);
}
});
});
};
How do I include a virtual field in a JSON response
const ItemSchema = mongoose.Schema({
name: String,
time: { type: Date, default: Date.now }
});
ItemSchema.virtual('timeleft').get(function() {
this.timeleft = 24
var currentTime = moment();
var timeStored = moment.utc(this.time).local().format();
this.timeleft -= currentTime.diff(timeStored, 'h');
});
API call
app.get('/getAllItems', function(req, res, next) {
Item.find({}, function(err, items) {
res.json(items);
});
});
So technically the response won't include virtual timeleft field. Am I missing something?
[
{
name: "nike",
time: "21/2/22"
},
{
name: "adidas",
time: "21/2/22"
},
]
// use Schema like this
const ItemSchema = new Schema({
name: String,
time: { type: Date, default: Date.now }
}, {
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
ItemSchema.virtual('timeleft').get(function() {
// this.timeleft = 24
var currentTime = moment();
var timeStored = moment.utc(this.time).local().format();
console.log(" ====== 000 ======== ", currentTime.diff(timeStored, 'h'))
return this.timeleft = currentTime.diff(timeStored, 'h');
});
const Item = mongoose.model('Item', ItemSchema);
new Item({
name: 'Axl'
}).save((err, result) => {
console.log("=== err ", err, "=== result ", result)
});
Item.find({}, function(err, items) {
console.log("=========", items)
});
According to Mongoose docs Mongoose virtuals are not stored in MongoDB, which means you can't query based on Mongoose virtuals.
// Will **not** find any results, because `domain` is not stored in
// MongoDB.
const doc = await User.findOne({ domain: 'gmail.com' });
doc; // undefined
If you want to query by a computed property, you should set the property using a custom setter or pre save middleware.
Modify your schema as shown below:
const ItemSchema = mongoose.Schema({
name: String,
time: { type: Date, default: Date.now },
toObject: { virtuals: true }, // <-- These properties will configure
toJSON: { virtuals: true } // model to include virtuals
});
Modify your API call as follows:
app.get('/getAllItems', function(req, res, next) {
Item.find({}, function(err, items) {
res.json(items.toObject()); // <-- use .toObject() or .toJSON()
});
});
I am using mongoosastic for performing search operation in mongoose.I have followed the instructions give in this mentioned link here but i am not getting the expected output.When i used the search query i am getting
{
"status": "404",
"message": "Not Found"
}
var express = require('express');
var mongoose = require('mongoose');
var mongoosastic = require('mongoosastic')
/*
var textSearch = require('mongoose-text-search');
var lmongo = require('lmongo');
*/
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname + '/public/app'));
var port = 9200;
app.listen(port, function() {
console.log("listening on", port);
});
var router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(router);
mongoose.connect('mongodb://localhost/search');
var Schema = mongoose.Schema;
var customerSchema = new mongoose.Schema({
customerDetails: {
name: {
type: String,
es_indexed: true
},
email: String
},
Description: String,
createdAt: {
type: Date,
default: Date.now
},
updateAt: {
type: Date,
default: Date.now
},
}, {
strict: false
}, {
collection: "customerDetails"
});
customerSchema.pre('update', function() {
this.update({}, {
$set: {
updateAt: new Date()
}
});
// next();
})
customerSchema.plugin(mongoosastic, {
hosts: [
'localhost:9200'
]
});
var Customer = mongoose.model('customer', customerSchema),
stream = Customer.synchronize(),
count = 0;
stream.on('data', function(err, doc) {
count++;
});
stream.on('close', function() {
console.log('indexed ' + count + ' documents!');
});
stream.on('error', function(err) {
console.log(err);
});
/*###################################################################################################*/
router.route('/cust/index/search') /*enabling search using mongoosastic*/ /*getting as msg not find */
.get(function(req, res) {
Customer.search({
query_string: {
query: "Sures"
}
}, function(err, results) {
if(err)
res.send(err);
res.send(results);
console.log(results);
})
})