Remove an object by an id in mongodb and mongoose - node.js

I'm getting an error on robots.remove stating robots is not defined, But I can't possibly figure out exactly why. Please help. thank you.
mongoose.connect('mongodb://localhost/robots'); //connecting to localdb
router.delete('/:id', function(req,res){
var id = req.params.id;
console.log(id);
robots.remove({_id:ObjectId(id)}, function(err, result){ //undefined??
if (err) return res.status(500).send({err: 'Error: Could not delete robot'});
if(!result) return res.status(400).send({err: 'Robot bot deleted from firebase database'});
console.log('deleted!!!');
res.send(result);
});
});

You have to load the user model first.
var robots = require('../app/models/robots');//Load the model
robots.js file should look like this:
var mongoose = require('mongoose');
var robotSchema = mongoose.Schema({
//Your schema here
});
module.exports = mongoose.model('robots', robotSchema);

Related

How to use mongoose module in node.js to get one record from mongo db

I am trying to retrieve data from MongoDB in nodejs. The items have slightly different structure ,so I do not want to use strict schema. My code is:
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const testDataSchema = new Schema({ any: {} })
const TestData = mongoose.model('my_collection_name', testDataSchema);
var url = "mongodb://myurl";
mongoose.connect(url);
mongoose.connection.once('open', function(){
console.log('connected!!!');
}).on('error', function(error){
console.log('error!!!', error);
});
TestData.findOne({}).then(function(result){
console.log('Result', result);
})
It prints:
connected!!!
Result null
The collection defenitelly has many records. What is the problem here and how to resolve it?
Try
TestData.find(function (err, products) {
if (err) {
res.send(err);
}
console.log(products);
});
also make sure that TestData is a model object

Mongoose findById is returning null

So I have this schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TreeSchema = new Schema({
}, { collection: 'treeLocations' });
var TreeDetailsSchema = new Schema({
}, { collection: 'treeInfo' });
module.exports = mongoose.model('Tree', TreeSchema);
module.exports = mongoose.model('TreeDetail', TreeDetailsSchema, "treeInfo");
And I am calling by ID like this:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
router.route('/api/trees/:tree_id')
.get(function(req, res) {
TreeDetails.findById(req.params.tree_id, function(err, treedetail) {
if (err)
res.send(err);
res.json(treedetail);
});
});
For some reason - http://localhost:3000/api/trees/5498517ab68ca1ede0612d0a which is a real tree, is returning null
Something that might help you help me:
I was following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
The only thing I can think of that changed is that I have a collection name. Might that be it?
The step that I don't see is how you actually connect to MongoDB and after that, how you get the Model from the connection.
// connect to MongoDB
var db = mongoose.createConnection('mongodb://user:pass#host:port/database');
// now obtain the model through db, which is the MongoDB connection
TreeDetails = db.model('TreeDetails');
This last step is how you associate your model with the connected mongo database.
More info on Mongoose.model
There are several ways to establish a connection to MongoDB with mongoose, the tutorial uses:
mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o');
(Personally I prefer the more explicit mongoose.createConnection as shown in the example)
(I used mongoose 4.3.1 for this example)
My steps to reproduce, in order to provide a working example (without creating a webservice for it):
var mongoose = require('mongoose'),
TreeDetails, db;
// create the model schema
mongoose.model('TreeDetails', mongoose.Schema({
// .. your field definitions
}, {collection: 'treeInfo'}));
db = mongoose.createConnection('mongodb://user:pass#host/example');
TreeDetails = db.model('TreeDetails');
TreeDetails.findById('5671ac9217fb1730bb69e8bd', function(error, document) {
if (error) {
throw new Error(error);
}
console.log(document);
});
Instead of:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
try:
var mongoose = require('mongoose'),
TreeDetails = mongoose.model('TreeDetail');
Defining the collection name shouldn't give you any issues. It's just what the collection will be called in the database / when using the mongo shell.
And just to be sure, try logging req.params.tree_id before calling findById to make sure it's coming through as you suspect.

Mongoose, MongoDb, Node. Mongoose object not registering find()

When i'm getting to my routes and requesting to getUSers from my mongoDB it says the User.find() is not defined. Sorry in advance if i use incorrect terminology i'm jumping in face first.
I'm assuming my routing is done incorrectly somewhere or i didn't include one file somewhere I'm hoping ya'll can help me determine if i'm either storing a file incorrectly in my structure, calling a file at the wrong time, or not initializing a variable correctly? Thanks for the help in advance.
Do i need an additional plugin to read and write to the database?
I keep getting the the following error it says usercontroller.js:20
Error: <!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>undefined is not a function</h1><h2></h2><pre>TypeError: undefined is not a function
at getUsers (c:\Users\Ravenous\kitchen\routes\user_api.js:5:10)
at c:\Users\Ravenous\kitchen\routes\user_api.js:26:3
file structure in case it helps
-bin
-node_modules-\
-user-app-\
-user.js //this is the model written with mongoose schema
-public-\
-html
-images
-javascripts-\
-userController
-userService //AngularJS factory
-stylesheets
-index.html
-routes-\
-user_api.js //with other useful routes inside.
-views //has some jade view engines that came with express-generator
-app.js
-package.JSON
I have this for the user model -- file: node_modules/user-app/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
user_name: String,
password: String,
email: String,
location: String,
date_created : {type: Date, default: Date.now}
});
var User = mongoose.model('User', UserSchema);
module.exports= {User:User};
I then import user.js file to the ./routes/user_api.js file which looks like this
user_api.js :
var User = require('./node_modules/user-app/user');
function getUsers(res){
User.find().populate('users').exec(function(err, users){
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err){
res.send(err)
}else{
console.log(users[0][0].name)
res.json(users); // return all users in JSON format
db.close();
}
})
};
module.exports = function(app) {
// api -----------------------------------------------------------
// get all users
app.get('/node_modules/user-app/user', function(req, res) {
// use mongoose to get all users in the database
getUsers(res);
});
// create user and send back all users after creation
app.post('/node_modules/user-app/user', function(req, res) {
// create a user, information comes from AJAX request from Angular
User.create({
user_name: User.user_name,
password: User.password,
email: User.email,
location: User.location,
done : false
}, function(err, todo) {
if (err){
res.send(err);
}else{
// get and return all the users after creating one
getUsers(res);
}
});
});
// delete a user
app.delete('/node_modules/user-app/user:user_id', function(req, res) {
User.remove({
_id : req.params.user_id
}, function(err, user) {
if (err)
res.send(err);
getUsers(res);
});
});
};
I'm adding this user_api route and get method to the app.js file like so
// loading some required modules above this
var app = express();
var user = require('./routes/user_api')(app);
to handle the Angular and Node connection and state sharing i'm using the following
userController.js:
(function(){
'use strict'
var userCtrl = angular.module("userController",[]);
console.log('userController init')
userCtrl.controller('UserController', ['$scope','$http','Users',function($scope,$http,Users){
$scope.users = {};
$scope.loading = true;
console.log ("user init");
Users.get()
.success(function(data){
$scope.users = data;
$scope.loading = false;
console.log(data)
})
.error(function(err){
console.log('Error: ' + err);
});
$scope.createUser = function(){
if($scope.users.user_name != false){
console.log($scope.users.user_name)
$scope.loading = true;
Users.create($scope.users)
.success(function(data){
$scope.loading=false;
$scope.users = data;
console.log(data);
})
.error(function(err){
console.log('Error: ' + err);
});
}
};
}]);
})();
Change the line where you require User to
var User = require('./node_modules/user-app/user').User;
This is because in your export statement when you define a user you have the line:
module.exports = {User:User};
So, you are exporting an object that has a User property on it.

mongodb + mongoose: query not entering .find function

I am getting start with mongodb and mongoose but am having problems querying a database. There are a number of tutorials online for what I am trying to do but it just doesn't seem to work for me. My problem is that the .find() function is not even being called and the collection is not being displayed. I have a collection called Subjects in which I know there are some values (I manually entered them in the mongodb command line). I only tried including pertinent code but let me know if anything else is needed. Thanks in advance.
app.js file
require('./models/model.js');
var conn = mongoose.createConnection('mongodb://localhost/test');
var Subject = mongoose.model('Subjects');
Subject.find( { }, function (err, subjects) {
if(err) console.log("Error"); // There is no "Error"
console.log("Made it"); // There is no "Made it"
console.log(subjects);
});
model.js file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SubjectsSchema = new Schema ({
subject: { type: String }
});
module.exports = mongoose.model('Subjects', SubjectsSchema);
Call mongoose.connect instead of mongoose.createConnnection to open the default connection pool that will be used by models created using mongoose.model:
mongoose.connect('mongodb://localhost/test');

Mongoose findById Route Issue

I'm writing a web application primarily to serve as a shopping cart. The landing/homepage of the app reflects products that are currently available for sale. What I'd like to do is route to each product using the product ID. I've defined a product model (adminProductModel) as follows:
'use strict';
var mongoose = require('mongoose');
var productModel = function () {
//Define a super simple schema for our products.
var productSchema = mongoose.Schema({
name: String,
price: Number,
productImg: String,
description: String
});
return mongoose.model('Product', productSchema);
};
module.exports = new productModel();
I'm able to post, and get, and delete products using the above model via an admin controller. Works great! I've then gone ahead and created an items controller, model and template, which are defined as below, with the intention to route from the homepage(index.dust) to an item's page using the item/product's id.
The item controller:
'use strict';
var ItemModel = require('../../models/adminProductModel');
var db = require ('../../lib/database');
module.exports = function (router) {
router.get('/index/:id', function (req, res) {
db.ItemModel.findById({_id: req.params._id}, function (err, prod){
if(err){
console.log('FindById filter error:', err)
}
var model = {product: prod}
res.render('item/index', model);
});
});
};
The item model:
'use strict';
module.exports = function ItemModel() {
return {
name: 'item'
};
};
The relevant code on the homepage (index) is:
The template (using dust as rendering engine):
{>"layouts/master" /}
{<title}
Greatness!
{/title}
{<body}
{?products}
{#products}
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img src="img/photo.png" alt="photo" width ="260" height = "180"/>
<center>
<h5>{.name}</h5>
<p>${.price}</p>
Buy
</center>
</div>
</div>
{/products}
{/products}
{/body}
When the anchor tag is clicked, it routes to correct ID, from the index page, but throws the following file not found error "URL /index/542237117b5f3e72136d70c5 did not resolve to a route".
What am I doing wrong here? I know I have to query the database for the products by its unique objectId. Am I implementing this wrong? If so, why does it resolve to a file not found error or at least render the correct markup?
Thanks a ton in advance. I've spend a few days thinking about this and I've exhausted all my approaches to solve this. I've included the database for completeness:
use strict';
var mongoose = require('mongoose');
var db = function () {
return {
config: function (conf) {
mongoose.connect('mongodb://' + conf.host + '/' + conf.database);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
console.log('db connection open');
});
}
};
};
module.exports = db();
Would it perhaps be wise to define my itemModel with a separate schema? This seems redundant and more error prone. I'm going to read further into this and home for some feedback from here. Thanks again.
Hi your are getting id value from params but it is :id not :_id
you are doing like this
console.log("id value : "+req.params._id)
db.ItemModel.findById({_id: req.params._id}, function (err, prod){
it should be like this
console.log("id value : "+req.params.id)
db.ItemModel.findById({_id: req.params.id}, function (err, prod){

Resources