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);
})
})
Related
the program doesnt show errors but when i run it on browse all i get is 2 brackets
here is my code
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const CompteModel = require('./models/Compte.js');
mongoose.connect('mongodb://localhost:27017/école');
app.get("/getCompte", (req, res) => {
CompteModel.find({}, (err, result) => {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
app.listen(3001, () => {
console.log("Hello");
});
Here is the schema of the collection "Compte".
const mongoose = require("mongoose");
const CompteSchema = new mongoose.Schema({ login: { type: String, required: true, }, password: { type: String, required: true,
},
});
const CompteModel = mongoose.model("Compte",CompteSchema); module.exports = CompteModel;
It does not return anything back (hang state) and i see in console
{ _id: 5f05d1527de7984a2c998385, name: 'alexa', age: 12 }. I tried both method promise and callback but still same. Can you guess what could be the issue?
const express = require('express');
const app = express();
const mongoose = require('mongoose');
app.use(express.json());
const TestModel = mongoose.model(
'test',
new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
}),
);
app.post('/test', async (req, res, next) => {
const testUser = req.body;
const Test = new TestModel(testUser);
console.log(Test);
/* Test.save(function (err, doc) {
if (err) {
return res.json({ message: 'something went wrong' });
}
res.json(testUser);
}); */
await Test.save();
res.json(testUser);
});
app.listen(4000, () => {
console.log('playground is up');
});
I am creating an express server in which I am trying to find the tracks in my database. Even though I have created the model to exactly how the attributes are in my database it still returns me an empty array. Please help
app.js
require('./config/config');
require('./db');
var Track = require('./models/track.model');
const mongoose = require('mongoose'),
express = require('express'),
bodyParser = require('body-parser');
var app = express();
const connection = mongoose.connection;
connection.once('open', () => {
console.log('MongoDB database connection established successfully!');
});
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/', function(req, res) {
Track.find({}, function(err, tracks) {
if (!err) {
console.log(tracks);
process.exit();
}
else {
throw err;
}
});
res.sendFile('index.html', {root: __dirname});
});
app.listen(process.env.PORT, ()=> console.log(`Server started at port: ${process.env.PORT}`));
track.model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let Track = new Schema({
Position: {
type: Number
},
Track: {
type: String
},
Artist: {
type: String
},
Streams: {
type: Number
},
Url: {
type: String
},
Date: {
type: String
}
});
module.exports = mongoose.model('Track', Track);
You need to bind Schema to collection like this:
let Track = new Schema({
Position: {
type: Number
},
Track: {
type: String
},
Artist: {
type: String
},
Streams: {
type: Number
},
Url: {
type: String
},
Date: {
type: String
}
}, { collection : 'spotifyCharts' });
if (!err){
console.log(tracks);
//Convert to JSON format
res.json(tracks)
process.exit();
}
2.
Test along with Collection Name in module.exports
module.exports = mongoose.model('Track', Track, 'CollectionName')
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
});
My code is(server.js) :
var express = require('express');
var bodyParser = require('body-parser');
var customerr = require('./customer')
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/customers');
app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.post('/customers', function (req,res){
console.log("POST: ");
console.log(req.body);
var custom = new customerr({
name : req.body.name,
mobile : req.body.mobile,
phone : req.body.phone,
address :req.body.address,
dob : req.body.dob,
email : req.body.email});
custom.save(function (err) {
if (!err) {
console.log(custom); // doubt in this line
console.log("created");
} else {
return console.log(err);
}
});
return res.send(custom);
});
Mongoose schema(I don't think thats there is any error in it.) (customer.js):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var customerSchema = new Schema({
Name: { type: String },
Mobile: { type: String },
Number: { type: String },
Address: { type: String },
DOB: { type: String },
Email:{ type: String }
});
var customerr = mongoose.model('customerr', customerSchema);
module.exports =customerr;
My controller part :
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");
var refresh = function() {
$http.get('/customers').success(function(response) {
console.log("I got the data I requested");
//console.log(response);
$scope.customers = response;
$scope.customer = "";
});
};
refresh();
$scope.addCustomer = function() {
console.log($scope.customer);
$http.post('/customers', $scope.customer).success(function(response) {
console.log(response);
refresh();
});
};
doubt : In app.post() the output shown is given below :(POST is printed, req.body gets printed, but when I console.log(custom) only object id is printed nothing else, as if the req.body is not saving in custom object)
POST:
{ name: 'ds',
mobile: 'adas',
phone: 'dasd',
address: 'asd',
dob: 'asdas',
email: 'das' }
{ __v: 0, _id: 58bb591a7cdbe0b534000001 }
created
I found where the error was, don't worry all your code is fine. Add this above the app.use(bodyParser.json()) line:
app.use(bodyParser.urlencoded({
extended: true
});
It worked after I added that, cheers.