Im trying to use mongoosastic for searching purposes, but I keep getting 'No Living connections' error and mapping problem
Here's the code
var mongoose = require('mongoose');
var mongoosastic = require('mongoosastic');
var Schema = mongoose.Schema;
var JobSchema = Schema({
category: { type: Schema.Types.ObjectId, ref: 'Category', es_indexed:true},
title: { type: String, es_indexed:true },
});
JobSchema.plugin(mongoosastic);
module.exports = mongoose.model('Job', JobSchema);
routes.js
var Job = require('../models/job');
Job.createMapping(function(err, mapping) {
if (err) {
console.log('error creating mapping (you can safely ignore this)');
console.log(err);
} else {
console.log('mapping created!');
console.log(mapping);
}
});
app.post('/search', function(req, res, next) {
Job.search({query_string: {query: req.body.q}}, function(err, results) {
if (err) return next(err);
res.send(results);
});
});
I keep getting this error,
Can anyone with experience in using mongoosastic tell,me how do i fix this problem?
When adding the plugin to your JobSchema model, you need to pass a second parameter with how to connect to Elasticsearch:
JobSchema.plugin(mongoosastic, {
hosts: [
'localhost:9200'
]
});
You can also re-use an Elasticsearch client object if you have one ready.
var esClient = new elasticsearch.Client({host: 'localhost:9200'});
JobSchema.plugin(mongoosastic, {
esClient: esClient
})
I am also facing same issue but I solved now using below method
Its very simple : you have to install elastic search in your local or anywhere else
Download elastic search http://www.elastic.co/downloads/elasticsearch
Extract folder
go to folder from cmd or Treminal find bin folder and inside that folder run elastic search script
And in nodejs code by default it will link to localhost:9200 so no need to use
new elasticsearch.Client({host: 'localhost:9200'}) , but if your elastic search deloyed some where else then you have to use above client method
I think you have to create a client and pass it into the plugin, but use ip addresses that is what worked for me.
// http://127.0.0.1:9200 == http://localhost:9200
var esClient = new elasticsearch.Client({host: 'http://127.0.0.1:9200'});
JobSchema.plugin(mongoosastic, {
esClient: esClient
})
Note: if you were not previously using elasticsearch you might have to re-index your documents (I had to, but I may have done something wrong)
Referencing this answer: https://stackoverflow.com/a/30204512/1146562
from that answer you can pass host straight into the plugin and do not have to create the client.
Related
There is a code:
const { MongoClient } = require('mongodb')
const db = MongoClient.connect('mongodb://172.17.0.2:27017/test')
db
.then(
async dataBase => {
eduDb = dataBase.db('edu-service-accounts')
const accounts = eduDb.collection('accounts')
await accounts.createIndex({ email: 1 }, { unique: true })
accounts.insertOne({ email: '123' })
}
)
Code above creates an index, but that is no unique. I already read official docs for native mongoDB driver, but can't handle it.
And yes, I've deleted all old indexex before testing that code.
Can someone please show a code that really create an index with unique.
I mean not part of official doc, or something like that - I need code that works.
NOTE: I tested that code with local db and mlab - the same result.
Like the documentation says: db.createIndex(collectionname, index[, options], callback) the creation returns an index. Try to log the result of the callback. Maybe you are getting an error from the db.
Try something like:
// your connection stuff
accounts.createIndex({ email: 1 }, { unique: true }, function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
}
});
After that please provide us the logs.
I'm currently trying to find all the documents that have a certain value of 'bar' in the key 'foo'. Using mongodb and nodejs.
When I try to run this I get:
"TypeError: Cannot read property 'find' of undefined" error return.
If I try using findOne() it'll just return the first document that has the document with the value "bar" for the key "foo", however there are 3.
module.exports = function(app, db) {
app.get('/foo', (req, res)=>{
db.collection('barCollection').find({foo: {$all: ['bar']}}
,(err, item)=>{
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
};
Thanks
Paul is right, there is some issue in your code which is why it's returning null.
Here try this snippet. I'm using 2 files for demo.
model.js
const mongoose = require('mongoose');
mongoose.connect('mongo_url');
var barSchema = new mongoose.Schema({
// your schema
});
module.exports = mongoose.model('Bar', barSchema);
main.js
var BarCollection = require('./models'); // assuming both files are in same directory.
BarCollection.find({foo: {$all: ['bar']}}
,(err, item)=>{
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
};
Basically what I am trying here is:
separate MongoDB model code in separate files
Import mongo collection in API files for CRUD operations
db.collection('barCollection') is returning null for some reason. You'll need to figure out why, it's probably somewhere else in your code since you don't have the setup logic here.
I'd look at whether mongodb was connected properly (i.e. is the db instance you're passing that function actually connected to the database), is mongodb running and available on the port you configured it with, etc.
Using this code to create a collection on MongoDB database hosted on mlab. But somehow it does not seems to be working. Is there something I am missing in this code? .save() function does not seem to be firing at all. Can it be due to my schema?
var mongoose= require('mongoose');
var Schema= mongoose.Schema;
app.use(express.static(__dirname+'/views'));
app.use(express.static(path.join(__dirname, 'public')));
//connect to mongo db database
mongoose.connect('mongodb://blaa:blaa#ds127132.mlab.com:27132/vendor');
//vendor schema
var vendorSchema= new Schema({
name:String,
image: { data: Buffer, contentType: String },
vendortype:String,
location: {
type: [Number], // [<longitude>, <latitude>]
index: '2d' // create the geospatial index
},
contactinfo:String,
description:String
});
//creating a model for mongoDB database
var Vendor= mongoose.model('Vendor',vendorSchema);
//just putting a sample record data
var imgPath = 'public/images/background.jpg';
var one = Vendor({
name: 'Justin Motor Works',
vendortype: 'Automobile',
contactinfo:'6764563839',
location: {
type:[23.600800037384033,46.76758746952729]
},
image: {
data: fs.readFileSync(imgPath),
contentType: 'image/jpg'
},
description: 'Motor workshop'
}).
save(function(err){
if(err)
throw err;
else {
console.log('create record failed');
}
});
mongoose.connect is an asynchronous function, you need to put your code inside a callback or promise.then(function(){.
Try this:
mongoose.connect('mongodb://blaa:blaa#ds127132.mlab.com:27132/vendor', function(error) {
if (error)
//handle error
//Your code
});
Or this:
mongoose.connect('mongodb://blaa:blaa#ds127132.mlab.com:27132/vendor').then(
() => {
//Your code
},
err => {
//Your error handling
}
);
Notice the error handling, it's important to know what caused the error for future debugging.
Also change the JSON structure of location when you are saving it as #NeilLunn said in the comments to something like this:
location: [23.600800037384033,46.76758746952729],
type in mongoose means actually defining the type of the key, and not a nested type key.
I have a simple mongoose model on which I call find with limit max 100 it calls the done callback:
this.find({}).limit(100).exec(done);
The callback is never called If I modify this line into (or any higher number)
this.find({}).limit(101).exec(done);
There is no error anywhere, the database keeps working, but this node app freezes and must be restarted.
If I ssh into the server to connect to the same database and connect to mongo shell, on the same collection find({}) returns all ~700 collections in less than a sec.
When I cloned the same database to my local PC and run the app to connect to local database it worked, but the app freezes on the server if its connect to the database on the same server.
Any idea how to debug this one?
Edit1: Added model file:
Model file:
'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let foodSchema = new Schema(
{
name: Object,
type: String,
description: Object,
price: Number,
priceBig: Number,
active: Boolean
},
{
collection: 'foods'
}
);
let model = mongoose.model('food', foodSchema);
model.getAllFoods = function (done) {
this.find({}, done);
};
model.getActiveFoods = function (done) {
this.find({active: true}, done);
};
model.getFoodById = function (id, done) {
this.findOne({_id: id}, done);
};
module.exports = model;
Usage:
foodModel.getAllFoods(function (err, docs) {
if (err) {
res.sendStatus(500);
return;
}
res.send(docs);
});
getActiveFoods works just fine (returns 96 docs)
After the tip from JohnnyK I updated Mongoose from 4.1.11 to 4.3.7 and that fixed the issue.
I'm new to mongoose and I'm having a hard time finding the issue within my code. I'm building a REST server using Sails.js and Mongoose. I have a node module (e.g. "sails-mongoose") for exporting mongoose, where I also connect to my database:
var mongoose = require('mongoose');
mongoose.connect('mongodb://#localhost:27017/fooria');
module.exports = mongoose;
And in my model.js:
var adapter = require('sails-mongoose');
var schema = new adapter.Schema({
firstname: {
type: String,
required: true,
trim: true
}
});
module.exports = {
schema: schema,
model: adapter.model('Collection', schema)
}
In my controller's create method I have:
create: function(req, res, next) {
var userData = {firstname: 'Test'};
var users = new Users.model(userData);
users.save(function(err, data){
if (err) return res.json(err, 400);
res.json(data, 201);
});
}
When running create method, the entry is saved to the Mongodb collection but the callback is never reached. Can someone please help me on this track, as I found similar questions but none helped me though. Thanks!
I suppose your are using Express. According Express docs you are calling res.json using incorrect parameters (wrong order).
Correct format:
res.json(code, data)
Example:
res.json(500, { error: 'message' })