Mongoose Find Method Not Working - node.js

EDIT: Resolved. It was just missing a bracket at the end of the if statement.
Thank you for your time!
The line at which I used Hotel.find doesn't appear to be executed, so the code below it doesn't work at all. I didn't get any errors or warnings. It just doesn't do anything. I don't understand what I did wrong.
function getPlaces() {
mongoose.connect("mongodb://localhost:27017/gtdb");
var db = mongoose.connection;
db.on("error", console.error.bind(console, "Connection error:"));
db.once("open", function(callback) {
//Define the hotel schema.
var Schema = mongoose.Schema;
var hotelSchema = new Schema({
"PlaceName" : String,
"PlaceType" : String,
"PlaceAddress" : String,
"Telephone" : String,
"PlaceCity" : String,
"ZipCode" : Number,
"State" : String,
"Country" : String,
"EstimatedPrice" : Number,
"PhotoUrl" : String,
"OtherDetails" : String
});
var Hotel = mongoose.model("Hotel", hotelSchema);
if (searchtype == "Hotel") {
console.log("Request received for hotel data.");
Hotel.find(function(err, hotels) { //This is the line it won't execute.
var i;
console.log(hotels);
console.log("Find test");
for (i = 0; i < hotels.length; i++) {
dataarray[i] = hotels[i];
}
});
} else if (searchtype == "Event") {
Event.find(function(err, events) {
});
}
mongoose.disconnect();
}); //End of db.once function.
} //End of the getPlaces function.
Thank you for your time.

Related

insert and insertOne not a function and update not creating mongo ID

I thought I could read my way to this solution, but I cant see what im doing wrong.
Here is my model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var inspectSchema = new Schema({
_id: Object, // Mongo ID
property: String, // Property ID
room: String, // The room Name
item: Array // The Items text
});
module.exports = mongoose.model('inspectModel', inspectSchema, 'inspect');
And here is where I try to insert or insertOne
var inspectModel = require('../../models/inspectModel');
var inspectTable = mongoose.model('inspectModel');
inspectTable.insert(
{
"property" : inspectRecord.property,
"room" : inspectRecord.room,
"item" : inspectRecord.item
},
function (err, res) {
if (err) { return reject({err:true, err:"addInspect ERROR" + err}) }
else {
show("=====RESOLVE addInspect=====")
return resolve();
}
})
I tried
inspectTable.insert
inspectModel.insert
inspectTable.insertOne
inspectModel.insertOne
No matter what I always get
TypeError: inspectTable.insert is not a function
I also tried just update with { upsert: true } but then the mongo ID becomes null.
Any ideas?
The method you're looking for is create:
inspectTable.create(
{
"property" : inspectRecord.property,
"room" : inspectRecord.room,
"item" : inspectRecord.item
}, ...
However, your schema definition of _id: Object is likely wrong. Just leave any definition of _id out of your schema and it will use the default ObjectId, which is likely what you want.
You can try this
var insert_table = new inspectTable(
{
"property" : inspectRecord.property,
"room" : inspectRecord.room,
"item" : inspectRecord.item
});
insert_table.save(function (err, res) {
if (err) { return reject({err:true, err:"addInspect ERROR" + err}) }
else {
show("=====RESOLVE addInspect=====")
return resolve();
}
});

MongoDB and mongoose: how to add an object if it doesn't already exist

I am having some trouble with mongoDB/mongoose and node.js. I am used to SQL, and mongoDB is...hard! Here is my schema:
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var itemSchema= mongoose.Schema({
item_info : {
user_id : Number,
location : String,
item_id : Number,
title : String
},
item_hist : {
user_id : Number,
location : String,
item_id : Number,
founddate : String
}
});
module.exports = mongoose.model('item', itemSchema);
And I can add a new item by doing this:
var item= require('./app/models/item');
var item= new item();
item.item_info.user_id = 12345;
item.item_info.location = 'This address';
item.item_info.item_id = 4444;
item.item_info.title = 'New item';
item.save(function(err)
{
if (err) throw err;
});
What I want to be able to do is say: "look for an item with item_info.item_id 5555. if it exists, do nothing. if it doesn't exist, then add it to the database." I've read through so much mongodb and mongoose documentation, but between using dot notation and accessing through nodejs instead of command line mongodb, I still can't figure out how to do this. SQL seemed so much easier!
Just use this -
var query = { user_id: 12345, location: "This address", item_id: 4444, title: "New item" },
options = { upsert: true };
Model.findOneAndUpdate(query.item_id, query, options, function(error, result) {
if (error) return;
// do something with the document
});

MongoDB and Nodejs insert ID with auto increment

I am new to NodeJs and MongoDB, i want to insert row with auto increment primary key 'id'. also defined a function called getNextSequence on mongo server.
this is working perfect on Mongodb server
> db.user.insert({
"id" : getNextSequence('user_id'),
"username" : "test",
"email" : "test#test.com",
"password" : "test123"
})
now i want to insert from NodeJs.I have tried this but not working
db.collection('user').insertOne({
id : "getNextSequence('user_id')",
username : query.name,
email: query.email,
password: query.pass
}, function(err, result) {
assert.equal(err, null);
console.log("row insterted ");
callback();
});
Assuming that getNextSequence is a server-script function (i.e. a method you defined and saved via db.system.js.save), it is not callable outside of the server. One way to go is to use eval, which forces the server to evaluate a string as a js code, even though it is not a good practice. Here is an example:
db.eval('getNextSequence(\'user_id\')', function(err, result) {
db.collection('users').insert({
"id" : result,
"username" : "test",
"email" : "test#test.com",
"password" : "test123"
});
});
Another way is to follow the mongo tutorial and to implement the getNextSequence directly in NodeJS. The syntax is pretty much the same:
function getNextSequence(db, name, callback) {
db.collection("counters").findAndModify( { _id: name }, null, { $inc: { seq: 1 } }, function(err, result){
if(err) callback(err, result);
callback(err, result.value.seq);
} );
}
You then use it in your nodeJS code like:
getNextSequence(db, "user_id", function(err, result){
if(!err){
db.collection('users').insert({
"_id": result,
// ...
});
}
});
Note: of course, you need to have set the counters collection as explained in the docs.
You can also use "mongoose-auto-increment".
The code has just 4 lines
var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
autoIncrement.initialize(mongoose.connection);
userSchema.plugin(autoIncrement.plugin, 'user');
example :
npm i mongoose-auto-increment
connections.js :
const mongoose = require('mongoose');
require("dotenv").config;
const uri = process.env.MONGOURL;
mongoose.connect(uri, { useNewUrlParser: true }, (err) => {
if (!err) { console.log('MongoDB Connection Succeeded.') }
else { console.log('Error in DB connection : ' + err) }
});
require('../schema/userSchema');
userSchema.js :
var mongoose = require('mongoose'); // 1. require mongoose
var autoIncrement = require('mongoose-auto-increment'); // 2. require mongoose-auto-increment
var userSchema = new mongoose.Schema({
name: { type: String },
password: { type: String },
email: { type: String, unique: true, required: 'This field is required.' },
});
autoIncrement.initialize(mongoose.connection); // 3. initialize autoIncrement
userSchema.plugin(autoIncrement.plugin, 'user'); // 4. use autoIncrement
mongoose.model('user', userSchema);
To accomplish this, we will create a function that will keep trying to save the document untill it will have been saved with incremented _id
async function retryUntilSave(db, task) {
try {
const index = await db.collection('tasks').find().count() + 1;
const result = await db.collection('tasks').insertOne(Object.assign(task, { _id: index }))
} catch (error) {
if (error.message.includes("_id_ dup key")) {
console.log("ID already exists!")
console.log("Retrying...");
retryUntilSave(db, task)
} else {
console.log(error.message);
}
}
}
We can use task._id: index instead of Object.assign()
finally you can test this by making some concurrent requests
for (let index = 0; index < 20; index++) {
setTimeout(async () => {
await retryUntilSave(db, { title: "Some Task" })
}, 1000);
}
This function will handle easily if two or more tasks submitted at the same time because mogod throws error when we try to insert a document with duplicate _id, then we will retry saving the document again with incremented _id and this process will run until we save the document successfully !
You can also use "mongodb-autoincrement" module of node js. For example:
var autoIncrement = require("mongodb-autoincrement");
exports.yourMethod = function(newData, callback) {
autoIncrement.getNextSequence(db, your-collection-name, function (err, autoIndex) {
newData.id = autoIndex;
//save your code with this autogenerated id
});
}
You can use the below package on a model schema to auto-increment your collection field.
mongoose-auto-increment //you can download it from npm
Here I am not focusing on how to connect MongoDB. I just focus on how you can integrate auto increment in your model/collection/table.
const mongoose = require("mongoose"); //
const autoIncrement = require("mongoose-auto-increment");
const post_schema = new mongoose.Schema({
title: {
type: String,
required: true,
min: 3,
max: 225,
},
slug: {
type: String,
required: true,
},
});
autoIncrement.initialize(mongoose.connection);
post_schema.plugin(autoIncrement.plugin, {
model: "post", // collection or table name in which you want to apply auto increment
field: "_id", // field of model which you want to auto increment
startAt: 1, // start your auto increment value from 1
incrementBy: 1, // incremented by 1
});
module.exports = mongoose.model("post", post_schema);

Mongoose not storing a field

When i go and check my database ,i cant see the studentNamer field there. its like i am never saving it.cant seen to understand what is happening. Why would it be skipping one field which is of type string , while saving other files of type string?
var mongoose = require('mongoose/');
var Schema = mongoose.Schema;
var studentInfoSchema = new Schema({
tty: String,
StudentNamer : String,
id : Number,
tt: String,
numberOfterms : Number
}, {collection: 'studentInfoDatabaseModel'});
var studentInfoDatabaseModel=mongoose.model( 'studentInfoDatabaseModel', studentInfoSchema);
mongoose.connect( 'mongodb://localhost/sss' );
var db=mongoose.connection;
db
.on('error', console.error.bind(console, 'DB connection error.'))
.once('open', console.log.bind(console, 'DB Connection established.'));
var newItem=new studentInfoDatabaseModel({
tty:"kkk",
studentNamer : "sumiit",
id: 55,
tt: "dfdsffsdaaa",
numberOfterms: 4
});
mongoose.saveToDb=function(){
newItem.save(function(err,result){
if(err){
console.log("there was an err savin");
}
});
}
mongoose.findData=function(){
var posts = db.model('studentInfoDatabaseModel');
posts.find({id : 55}, function(err, calls) {
console.log(err, calls, calls.length); //prints out: null [] 0
var u1= calls[0].id;
var u= calls[0].studentName;
});
}
exports.mongoose=mongoose;
You declared it in the schema as StudentNamer (note the "S") but you are trying to save it as studentNamer : "sumiit" (note the "s"), so just change it to:
var studentInfoSchema = new Schema({
tty: String,
studentNamer : String,
id : Number,
tt: String,
numberOfterms : Number
}, {collection: 'studentInfoDatabaseModel'});

failing to run mongodb2.4 text search

When I run mongo db I get this :
$ ./mongo db
MongoDB shell version: 2.4.2
connecting to: db
Server has startup warnings:
** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
Mon Apr 22 19:25:54.938 [initandlisten] Index { v: 1, key: { type: "text", color: "text", category_A: "text", category_B: "text", category_C: "text" }, ns: "db.items", name: "type_text_color_text_category_A_text_category_B_text_category_C_text", sparse: false, background: false } claims to be of type 'text', which is either invalid or did not exist before v2.4. See the upgrade section: http://dochub.mongodb.org/core/upgrade-2.4
> db.adminCommand( { setParameter : 1, textSearchEnabled : true } )
{ "was" : false, "ok" : 1 }
> db.runCommand("text",{search:"le"})
{
"errmsg" : "exception: wrong type for field (text) 1 != 2",
"code" : 13111,
"ok" : 0
}
when I run the following code with nodejs I get -
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var Items = new Schema({
type : { type : String , default:""},
color : { type : [String] , default:""},
category_A : { type : String , default:""},
category_B : { type : String , default:""},
category_C : { type : String , default:""},
});
var textSearch = require("mongoose-text-search");
var ItemModel = mongoose.model('Item', Items);
Items.plugin(textSearch);
Items.index({
type :"text",
color :"text",
category_A :"text",
category_B :"text",
category_C :"text"
},
{
name: "best_match_index",
weights: {
type: 5,
color: 4,
}
}
)
ItemModel.textSearch('D', function (err, output) {
if (err)
console.log(err);
else
console.log(output)
})
running this I get :
ItemModel.textSearch('D', function (err, output) {
^
TypeError: Object function model() {
Model.apply(this, arguments);
} has no method 'textSearch'
Having a same issue here.
I resolved it by applying code from /mongoose-text-search/lib/index.js
YOURSCHEMA.statics.textSearch = function (search, o, cb) {
if ('function' == typeof o) cb = o, o = {};
if ('function' != typeof cb) {
throw new TypeError('textSearch: callback is required');
}
var model = this;
var lean = !! o.lean;
// mongodb commands require property order :(
// text must be first
var cmd = {};
cmd.text = o.text || this.collection.name;
cmd.search = search;
var keys = Object.keys(o);
var i = keys.length;
while (i--) {
var key = keys[i];
switch (key) {
case 'text':
// fall through
case 'lean':
continue;
case 'filter':
cmd.filter = model.find(o.filter).cast(model);
break;
case 'project':
// cast and apply default schema field selection
var query = model.find().select(o.project);
query._applyPaths();
var fields = query._castFields(query._fields);
if (fields instanceof Error) return cb(fields);
cmd.project = fields;
break;
default:
cmd[key] = o[key];
}
}
this.db.db.command(cmd, function (err, res) {
if (err) return cb(err, res);
if (res.errmsg) return cb(new Error(res.errmsg));
if (!lean && Array.isArray(res.results)) {
// convert results to documents
res.results.forEach(function (doc) {
if (!doc.obj) return;
var d = new model(undefined, undefined, true);
d.init(doc.obj);
doc.obj = d;
})
}
cb(err, res);
});
}
}
to my local schema file
One thing to double-check is that you're not overriding the statics property after you've applied the plugin. This is what was causing the problem for me.
mySchema.plugin(textSearch);
mySchema.index({ name: 'text' });
...
mySchema.statics = { ... }

Resources