foo.find(...).execFind is not a function - mongoose schema model - node.js

I have defined a custom type and I am trying to return all entries from mongo contained in the referenced collection:
Participant.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var participantSchema= new Schema({
email: String,
});
module.exports = mongoose.model('Participant', participantSchema, 'participants')
api.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Participant = require('../models/Participant');
router.get('/all', function(req, res) {
var participant = mongoose.model('Participant');
//var participant = new Participant();
console.log(participant);
participant.find().execFind(function (arr,data) {
res.send(data);
});
});
module.exports = router;
But due something fishy, my model does not extend (I assume the default prototype)
participant.find(...).execFind is not a function
TypeError: participant.find(...).execFind is not a function
at /Users/bogdan/private/appName/routes/api.js:13:24
Any help is highly appreciated...
Thanks

execFind was replaced with exec back in one of the 3.x releases of Mongoose.
So you must now call exec instead of execFind.

Related

nodejs getting double of records from mongodb

var express = require('express');
var router = express.Router();
var Product = require('../models/products');
/* GET home page. */
router.get('/', function(req, res, next) {
var products = Product.find();
res.render('shops/index', { title: 'Express' ,Product:products});
});
module.exports = router;
i am new to nodejs and mongodb .I have 5 record in database but the code above is returning 15 records from database
here is the model implemented
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
imagePath:{type: String,required:true},
title:{type: String,required:true},
description:{type: String,required:true},
price:{type: String,required:true},
});
module.exports = mongoose.model('Product',schema);
find is an asynchronous operation where the result is provided in a callback function. Querying for it would look like that:
Product.find({}, function(err, products) () {
res.json(products);
});
But i can't see why you are getting 15 results...

Module exports in mongoose

I'm a little confused by this part of mongoose, currently i am trying create the habit of structuring my project(using express-generator). I have these part of codes and i am trying to make a get request and return some value from the mongo but in my mind i am not reaching it right.
The app.js is basically the default when i run it for the first time, but to be clear i have line below for my route to work.
app.get('/login', usersRouter);
Then I have the users.js in the routes folder
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
//Connect to localhost
mongoose.connect('mongodb://localhost:27017/LCC');
//Bring models
let User = require('../models/user-model');
router.get('/login', function (req, res) {
User.find({}, function(err, result){
console.log(result);
});
});
And my model in the other folder:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//User Schema
var userProfile = new Schema({
username: String,
password: String
});
module.exports = mongoose.model('Users', userProfile);
My question is, what did i missed? Because in my mind it was supposed to work the console.log and retrieve all the users in mongo. But i only get [] in the terminal (there are six records in the database).
I just copied one route and not all of the code but if something is missing just tell me and i'll edit the post, with mongo driver i can do these queries but i am trying to learn this way by my own. And english is not my first language so sorry for any mistakes.
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/dbname");
var userSchema = mongoose.Schema({
name: String,
age: Number,
});
module.exports = mongoose.model("module", userSchema);

Why postman not send data

I'm a beginner with nodejs and express. I'm trying to use postman's POST method but no data is getting sent. Here is my code
var express = require('express');
var userRouter = express.Router();
var userModel = require('../models/usermodels');
userRouter.route('/users')
.post(function(req,res) {
var users = new userModel(req.body);
users.name = req.body.name;
users.age = req.body.age;
users.save();
res.status(200).send(users)
})
Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UsersSchema = new Schema({
name:String,
age:Number
});
var model = mongoose.model('Users',UsersSchema);
module.exports = model;
Where is my error?
Here is img
You must make sure that you define all configurations BEFORE defining routes.I think you define after and it's reason why not work . If you do so, you can continue to use express.bodyParser().
Use debugging using console.log and also use error callback on save
Also use x-www-form-urlencoded (Content type) option when sending data from postman
var express = require('express');
var userRouter = express.Router();
var userModel = require('../models/usermodels');
userRouter.route('/users')
.post(function(req,res) {
//check here if request receive
console.log("requessssssssssssssssssss");
//check the data receive
console.log("dataaaaaaaaaaaaaa", req.body);
var users = new userModel(req.body);
users.name = req.body.name;
users.age = req.body.age;
//check if any error
users.save(function(saveError){
if(saveError){
return res.status(400).send(saveError)
}else{
res.status(200).send(users)
}
});
})

How do I partially update an array inside and object in MongoDB so the new value is added to the array

Given the following schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var favoriteSchema = new Schema({
dishes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Dish'
}],
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {
timestamps: true
});
var Favorites = mongoose.model('Favorite', favoriteSchema);
module.exports = Favorites;
and the following router
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.create(req.body,function(err,fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
module.exports = favoritesRouter;
Every time i do the post requires from postman, I`m attaching the dish ID to the body of the request.
{
"_id": "577a996155d73cf02b0d516f"
}
I could not come up with a solution to insert this ID into the array, instead of re-creating the whole object with only 1 id inside the array. Am i making something wrong, or something else has to be done in order to do the logic i want?
You're going to want to query the database to find the previously saved object, append to the array, mark as modified, then save. It will look something like this:
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.findById(someID, function(err, fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.markModified('dishes')
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
You'll need to figure out how you're getting the ID in there. You could use a dynamic endpoint:
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/:id')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
var someID = req.params.id
})
Or you could do a search for who posted it (.find({postedBy: req.decoded._doc._id},... instead of .findById(someID,...), or something else

Mongoose multiple connections

Currently I have this code for my connection mongoose.js:
var mongoose = require('mongoose');
var uriUtil = require('mongodb-uri');
var mongodbUri = 'mongodb://localhost/db_name';
var mongooseUri = uriUtil.formatMongoose(mongodbUri);
mongoose.connect(mongooseUri);
module.exports = mongoose;
File that requires the connection is test.js:
var mongoose = require('../model/mongoose');
var schema = mongoose.Schema({...});
How can I update mongoose.js to use multiple connections with mongoose.createConnection(...) function?
I start with changes only for one connection when I do changes like that:
var mongoose = require('mongoose');
mongoose.createConnection('mongodb://localhost/db_name');
mongoose.open('localhost');
module.exports = mongoose;
I get "undefined is not a function".
If I use this code:
var mongoose = require('mongoose');
db = mongoose.createConnection('mongodb://localhost/db_name');
db.open('localhost');
module.exports = mongoose;
I get "Error: Trying to open unclosed connection"
Any advice?
Mongoose handling connections via connections pool
http://mongoosejs.com/docs/connections.html
You can use server: {poolSize: 5} option for increase/decrease pool (number of parallel connections)
If you need connections to different databases look here
Mongoose and multiple database in single node.js project
Example of multiple connections:
var mongoose = require('mongoose')
var conn = mongoose.createConnection('mongodb://localhost/db1');
var conn2 = mongoose.createConnection('mongodb://localhost/db2');
var Schema = new mongoose.Schema({})
var model1 = conn.model('User', Schema);
var model2 = conn2.model('Item', Schema);
model1.find({}, function() {
console.log("this will print out last");
});
model2.find({}, function() {
console.log("this will print out first");
});
OK. With your example I found a solution that fit my needs.
mongoose.js
var mongoose = require('mongoose');
mongoose.main_conn = mongoose.createConnection('mongodb://localhost/main');
mongoose.admin_conn = mongoose.createConnection('mongodb://localhost/admin');
module.exports = mongoose;
content.js
var mongoose = require('../model/mongoose');
var schema = mongoose.Schema({...});
/// functions here
schema.statics.func_a(){...};
schema.statics.func_b(){...};
// And finaly updated only one line
//exports.Content = mongoose.model('Content', schema);
exports.Content = mongoose.main_conn.model('Content', schema);
The only thing, is it OK to add connection objects to mongoose object or may be there is more elegant solution.
config.js
module.exports = {
default: 'main',
main: 'mongodb://localhost/main',
admin: 'mongodb://localhost/admin',
};
connection.js
const mongoose = require('mongoose');
const config = require('./config');
mongoose.Promise = global.Promise;
function createConnection(name) {
return mongoose.createConnection(config[name]);
}
module.exports = createConnection(config[config.default]);
module.exports.on = createConnection;
model.js (custom class)
const connection = require('./connection');
class Model {
constructor(name, data) {
this.data = data;
return this.connection().model(name, data.schema);
}
connection() {
if (this.data.connection) {
return connection.on(this.data.connection);
}
return connection;
}
}
module.exports = Model;
user.js
const Schema = require('mongoose').Schema;
const conn = require('./connection');
const Model = require('./model');
const userSchema = new Schema({
name: String,
email: String,
password: String
});
// USING MONGOOSE MODEL
// default connection
const UserM1 = conn.model('User', userSchema);
// admin connection
const UserM2 = conn.on('admin').model('User', userSchema);
// USING CUSTOM MODEL
// default connection
const UserC1 = new Model('User', {
schema: userSchema
});
// admin connection
const UserC2 = new Model('User', {
schema: userSchema,
connection: 'admin'
});

Resources