Get Next and Previous MongoDB with Javascript - javascript

I have an Express app with MongoDB and Mongoose. The app displays image galleries for different projects which are all held in the DB. I'd like each image gallery to link to the previous and next projects held in the DB, so I'm trying to get the IDs of those projects and pass them into the EJS template:
app.get('/projects/:_id', function(req, res){
nextProject = Project.findById({_id: {$gt: req.params._id}}).sort({_id: 1 }).limit(1)
console.log('Next Project');
console.log(nextProject);
But this returns an error:
{ CastError: Cast to ObjectId failed for value "{ _id: { '$gt': '57d09754943f2403738edb04' } }" at path "_id"
How should I get the previous and next entries in the database? Actually it doesn't really matter if they are the previous and next entries in the DB, just as long as they're different from the one currently being displayed.
In case it's useful, here's the Project schema:
var mongoose = require('mongoose');
var projectSchema = new mongoose.Schema({
title: String,
description: String,
images: Array
});
module.exports = mongoose.model('Project', projectSchema);
Thank you!

You just need to change findById to find.
findById accepts the _id of the document you're looking to find, not a query object.

Related

Mongoose-fuzzy-searching returns empty array unless query is empty

I am working on a wiki-like website component and I am trying to implement a fuzzy search. I found a popular Node.js plugin on npmjs for a fuzzy search of a cloud mongoDB database handled with Mongoose. I installed and saved mongoose-fuzzy-searching and hooked it up to my model and route. Then I updated all of the models, resaving each's value for the field I wanted to index. I can seem to call the function on a model, and it seems like there's an index on MongoDB Atlas, but it returns an empty array instead of any results. 2 questions:
Am I doing something wrong, or is there something I am missing?
Is there a better node library that's free? (*Free on heroku, which I think eliminates flexsearch as an option)
Here's my code.
Model:
const mongoose = require("mongoose"),
mongoose_fuzzy_searching = require('mongoose-fuzzy-searching'),
Schema = mongoose.Schema;
const IssueTemplateSchema = new Schema({
name: String,
info: String,
image: String,
tags: [{type: Schema.Types.ObjectId, ref: "Tag"}],
active: {type: Boolean, default: true},
instances: [{type: Schema.Types.ObjectId, ref: "LocalIssue"}],
issues: {type: Schema.Types.ObjectId, ref: "Issuegraph" },
});
IssueTemplateSchema.plugin(mongoose_fuzzy_searching, { fields: ['name'] });
module.exports = mongoose.model("IssueTemplate", IssueTemplateSchema);
An update to all of the issuetemplate models:
const express = require('express'),
router = express.Router(),
Issue = require('../api/issue/issue.template');
router.get("/createIndex", async (req, res) => {
Issue.find({}, async (err, issues) => {
if(err){console.log(err)}else {
for(issue of issues){
if(err){console.log(err)}else{
const name = issue.name;
await Issue.findByIdAndUpdate(issue._id, {name: name}, {strict: false});
}
}
}
});
return res.send("done");
});
Route:
router.get("/search", (req, res) => {
console.log(req.query.target);
let searchTerm = "";
if(req.query.target){
searchTerm = decodeURIComponent(req.query.target.replace(/\+/g, ' '));
}
Issue.fuzzySearch(searchTerm, (err, issue)=> {
if(err){
console.log(err);
res.send("Error fuzzy searching: " + err);
} else {
returnResult(issue);
}
});
function returnResult(result) {
console.log(result);
return res.send(result);
}
});
When I ran
npm install --save mongoose-fuzzy-searching
I received an error saying it needed mongoose 5.10, and I have 5.11, but it seemed to at least plug in. Can't see why When I send a request through Postman, I receive an empty array. If I leave the query blank, then I get everything. I have reset Node and am using mongoDB Cloud, where I see an index has been created. Is there perhaps a reset of the cloud database I would need to do (I don't know of such a thing), or is resetting the server enough? My knowledge level is: studying to be a freelance web developer and would appreciate any general tips on best practice, etc.
Mongoose need to define schema. which makes it slow and find() method is good for development, not for production level. Also ,This Process is outdated. You are working on MongoDB. if you need search then take a look into MongoDB atlas Full Text-Search.It includes all of those searching features like: autocomplete, Fuzzy Search everything.
It seems like my update operation was not actually updating the field I wanted to update, because findByIdAndUpdate() returns a query and I wasn't executing that query (with .exec() ). Await was also being used incorrectly because its purpose is not just to pause in an async function like I thought, but to wait for a promise to fulfill. A query is not a promise, and await is specifically for promises. Before I learned these details, I solved my problem in another way by using .find() , then .markModified("name") , then .save() . Once I did that, it all worked!

MongoDB/javascript/node.js/typescript : How to connect to two mongoose models?

I am creating an api, and i'm working with MongoDB as a dataBase,
I've already created one model :
in database.ts
import mongoose = require('mongoose');
const schema = new mongoose.Schema({
id: String,
username: String,
gender: String,
birthdate: String,
password: String
});
export default mongoose.model('users', schema);
i'm connecting to the database using :
mongoose.connect('mongodb://localhost:27017/users', {useNewUrlParser: true});
in app.ts.
In utils.ts I imported the model like this :
import userDB from './database';
and for example, to retrieve all the users inside the database I use this (still in utils.js) :
const users = await userDB.find();
Now my problem is that I want to have another model, which will have some keys insides, that I can retrieve and check if for example what the user has given to me correspond to one of the keys
I tried to search on most of the websites but didn't find the right answer.
I hope you can help me.
Thanks you in advance.
PS: it's my first post here, so if I did something wrong or my problem is not clear, feel free to tell me
When you are connecting to Database you should connect to a project rather than to your schema like this
mongoose.connect('mongodb://localhost:27017/myProject', {useNewUrlParser: true});
You can replace myProject with whatever name you like. If the Project doesn't exist it will be created once you start your server and mongoDB is connected.
Then to retrieve all the users you can use this
import User from './user'; //Wherever your schema is
const Allusers = await User.find();
Now you can create as many Schema's you like and use it.

Mongodb does not save a document

I am trying to store some data from an HTML formulary. I send the data using the HTTP POST method and I received them using Express framework in Node.js. The data arrives and it seems to work, but when I try to store them into MongoDB using Mongoose, the database is created but no data is stored when I execute DB.sis_dictionary.find()
I've tried to build different types of schemas and models, but none seems to work. And I get no error from Node.js, it seems to be working, but the MongoDB database does not store anything.
const Mongoose = require('mongoose');
Mongoose.connect('mongodb://localhost:27017/sis_dictionary', {useNewUrlParser: true});
const Schema = Mongoose.Schema;
const wordSchema = new Schema({
word: String
})
const Word = Mongoose.model('Word', wordSchema);
app.post('/saveWord', (req, res) => {
var word = new Word({word: String(req.body)});
word.save(function(err){
if(err) {
return console.error(err);
} else {
console.log("STATUS: WORKING");
}
})
console.log(req.body);
})
server.listen(3000);
console.log("SERVER STARTUP SUCCESS");
In the console, I get the message: "STATUS: WORKING".
sis_ditionary is your DB name and Words should be your collection name. As mongoose automatically creates a plural name for collection from a model if model name not specified when creating from a schema
db.collection.find() is a command to find a collection data when using mongo-shell. Run below command to get data:
use sis_dictionary
db.Words.find()
To beautify result use pretty method
db.Words.find().pretty()
First command will select DB and second command list collection data.
So when you execute db.sis_dictionary.find() it won't work because sis_dictinary is your DB name.
Nodejs way with 'mongoose'
//Model.find({});
Word.find({});
Also, check this line var word = new Word({word: String(req.body)});
What does req.body have? If req.body is {word:"example word"} then you directly pass req.body to modal constructor ie new Word(req.body);
According to your database URL, mongodb://localhost:27017/sis_dictionary, sis_dictionary is the database name.
And according to your mongoose model, Word is your collection name.
When you save a document, it saves under a collection. So you have to make a query under the collections.
So when you try to get data using DB.sis_dictionary.find(), definitely it won't work.
Your query should be like db.collection.find()
Use the following query,
use sis_dictionary
db.words.find()
// for better view
db.words.find().pretty()
For more please check the documentation.
Thank you everybody. You were all right, it was a problem related to my collections names. db.words.find().pretty() worked perfectly!The problem is solved.

Mongoose is connected but can't find data

I have a problem and could really use some help.
We had an application that used MySQL and we are switching over to MongoDB.
We are using Node.js with Express and have MongoDB and Mongoose for the database
We have looked at the MongoDB and Mongoose documentation and searched for related questions on Stack Overflow but we seem to be missing something.
This is what we have in app.js:
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost:27017/DBName');
This is our usersModel.js
var db = require('mongoose');
var Schema = db.Schema;
var userSchema = new Schema({
u_id : Number,
u_name : { type: String, required: true },
u_lastname : String
});
module.exports = db.model('user', userSchema);
And this is what we use in the userController:
var User = require('../models/usersModel');
User.find({}, function(err, users) {
if (err) throw err;
console.log("Found users: ", users);
});
The console.log(db.connection.readyState); says it is connecting.
And the User.find() doesn't seem to give out an error, but instead gives an empty array/undefined.
We would really appreciate it if someone could tell us what we overlook.
Thanks in advance.
Not sure why anyone thought this was a good idea, but here's what mongoose does:
Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name.
As a bonus, it's in lower-case which sucks when you have table names with camel case convention.
You can fix it by setting below option in your scheme:
var userSchema = new Schema({..}, { collection: 'user' });
More on this here.
Your find() call looks fine to me.
Are you sure there are users in your collection? Does creating a new user throw an error that you didn't notice? Maybe you can verify that there are indeed users in your collection by popping open a terminal and writing:
> mongo
> use DBName
> show collections
> db.user.find()
And that will return all users that exist.
At: iuliu.net: We get both errors the first was [] and the second is undefined.
At JohnnyHK: Thank you for your submit, but we are sure the the user collection is in this database and the properties we search exists.
At Juuso: Thanks for your feedback your but in the mongo terminal we got the collection output.
Some one asked us a critical question if we tried this with monk. We
installed monk and we have find the database, collection and got
result back. We're still not sure what the problem with Mongoose was,
but with monk it works.
Thank you guys for your feedback and time.

Mongoose/Node server restart and duplicates

Ok so after a ton of trial and error, I've determined that when I drop a collection and then recreate it through my app, unique doesn't work until I restart my local node server. Here's my Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Services = new Schema ({
type : {type : String},
subscriptionInfo : Schema.Types.Mixed,
data : Schema.Types.Mixed
},{_id:false});
var Hashtags = new Schema ({
name: {type : String},
services : [Services]
},{_id:false});
var SubscriptionSchema = new Schema ({
eventId : {type: String, index: { unique: true, dropDups: true }},
hashtags : [Hashtags]
});
module.exports = mongoose.model('Subscription', SubscriptionSchema);
And Here's my route...
router.route('/')
.post(function(req, res) {
var subscription = new subscribeModel();
subscription.eventId = eventId;
subscription.save(function(err, subscription) {
if (err)
res.send(err);
else
res.json({
message: subscription
});
});
})
If I drop the collection, then hit the /subscribe endpoint seen above, it will create the entry but will not honor the duplicate. It's not until I then restart the server that it starts to honor it. Any ideas why this is? Thanks!
What mongoose does when your application starts and it itself initializes is scan your schema definitions for the registered models and calls the .ensureIndexes() method for the supplied arguments. This is the "by design" behavior and is also covered with this statement:
When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting the autoIndex option of your schema to false.
So your general options here are:
Don't "drop" the collection and call .remove() which leaves the indexes intact.
Manually call .ensureIndexes() when you issue a drop on a collection in order to rebuild them.
The warning in the document is generally that creating indexes for large collections can take some time and take up server resources. If the index exists this is more or less a "no-op" to MongoDB, but beware of small changes to the index definition which would result in creating "additional" indexes.
As such, it is generally best to have a deployment plan for production systems where you determine what needs to be done.
This post seems to argue that indexes are not re-built when you restart: Are MongoDB indexes persistent across restarts?

Categories