i'm having an issue querying my mongodb database. i'm using react js. the problem doesn't seem to be the connection because i can save to the database just fine, i can only assume its a syntax issue. i've looked around but couldn't find a fix. below is a snippet of code from the schema.js file and the index.js file:
Schema.js
//import dependency
var mongoose = require('mongoose')
var Schema = mongoose.Schema
//create new instance of the mongoose.schema. the schema takes an
//object that shows the shape of your database entries.
var UserSchema = new Schema({
socketId: String
})
//export our module to use in server.js
module.exports = mongoose.model('User', UserSchema)
index.js
var mongoose = require('mongoose')
var db = mongoose.connect('mongodb://mongodatabase', {
useMongoClient: true,
/* other options */
})
var UserSchema = require('../schema/Schemas');
function userExist(userList, username){
var usert = new UserSchema()
var query = usert.where({socketId: username})
query.findOne(function (err, usert) {
if (err) return handleError(err);
if (usert) {
// doc may be null if no document matched
}
});
return username in userList
// return query
}
I get the error : usert.where is not a function.
i tried using just find but i get the same error
any help would be welcome, Thank you
You should use .findOne function directly on your schema class instead of .where
Like this :
UserSchema.findOne({socketId: username}, function (err, usert) {
if (err) return handleError(err);
if (usert) {
// doc may be null if no document matched
}
});
.where must be used on query, not schema.
To use .where, you can do it like this :
User.findOne().where({ socketId: username }).exec( function (err, usert) {
if (err) return handleError(err);
if (usert) {
// doc may be null if no document matched
}
})
Related
I am attempting to build a Vue.js app with a MEVN stack backend and Vuex. I am configuring my Vuex action handler with a GET request that prompts a corresponding Express GET route to query data nested in Mongoose.
A username is passed into the handler as an argument and appended to the GET request URL as a parameter:
actions: {
loadPosts: async (context, username) => {
console.log(username)
let uri = `http://localhost:4000/posts/currentuser?username=${username}`;
const response = await axios.get(uri)
context.commit('setPosts', response.data)
}
}
The corresponding Express route queries activeUser.name, which represents the nested data in the Mongoose Model:
postRoutes.route('/currentuser').get(function (req, res) {
let params = {},
username = req.query.activeUser.name
if (username) {
params.username = username
}
Post.find(params, function(err, posts){
if(err){
res.json(err);
}
else {
res.json(posts);
}
});
});
Below is my Mongoose model, with activeUser.name representing the nested data queried by the Express route:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Post = new Schema({
title: {
type: String
},
body: {
type: String,
},
activeUser: {
name: {
type: String
}
}
},{
collection: 'posts'
});
module.exports = mongoose.model('Post', Post);
Even with this setup, the GET route does not appear to send a response back to the action handler. I thought adding username = req.query.activeUser.name in the express route would be the right method for querying the nested data in Mongoose, but apparently not. Any recommendations on how to configure the above Express route in order to query the nested data in the Mongoose model? Thanks!
name is inside activeuser so you need to construct params object variable like this:
postRoutes.route("/currentuser").get(function(req, res) {
let params = {
activeUser: {}
};
let username = req.query.activeUserName;
if (username) {
params.activeUser.name = username;
}
Post.find(params, function(err, posts) {
if (err) {
res.json(err);
} else {
res.json(posts);
}
});
});
Note that I also used activeUserName as query param like this: /currentuser?activeUserName=JS_is_awesome18
While sending a post request i written the following code :
var email = req.body.email ;
var newDetails = { email: email };
Details.create(newDetails);
console.log(newDetails);
while sending the request. The console.log shows me the correct details,
However in the mongo shell the only collection that exist is "details" and it's empty .
That's the Mongoose Schema:
var mongoose = require("mongoose");
var DetailsSchema = mongoose.Schema({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
I'm using NodeJS.
Thanks in advance.
Your Mongoose Model should be like
const mongoose = require("mongoose");
const Scheme = mongoose.Schema;
const DetailsSchema = new Scheme({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
Node js Code should be like
var detailsModel = require('../model/Details.js');//path of mongoose model
var detailsData = new detailsModel();
detailsData.email = req.body.email;
detailsData.save(function (err, savedJob) {
if (err) {
return res.send(err);
} else {
return res.send(savedJob);
}
});
To save data in mongoDB's Database
You can use this way
var detailsData = new detailsModel();
detailsData.save()
.then(business => {
res.status(200).json({'Details': 'newDetails added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
With this, you can also handle error easily.
I am trying to delete the entry from MOngoDb by using MEAN STACK with ANgular 4.(New to this technology)
typescript:
deleteitem(id){
let deleteresult;
let itemid = id;
this.dataService.deleteitem(itemid)
.subscribe(res =>deleteresult =res,
err => this.apiError = err,
)
};
dataservice:
deleteitem(itemid): Observable<any>{
let data =new URLSearchParams();
data.set('deleteId', itemid);
console.log(data.toString());
return this.http.post(URL, data.toString())
.map(res=> res.json())
.catch((error:any) => Observable.throw('Server Error To delete the item'));
}
Router.js
const ObjectID = require('mongodb').ObjectID;
router.post('/deleteitem', function(req, res){
MongoClient.connect('URL',function(err, client){
if (err) throw err;
var myDB = client.db('DbName');
var collection = myDB.collection('collectionName');
console.log(req.body);
//var objectId = collection.getObjectId();
collection.remove({_id: ObjectId(req.body.deleteId), function(err, result)
{
res.send((result==1)?{msg:deleted} : {msg:"error:"+ err});
}});
})
})
Error:
ObjectId is not defined.
Also the console.log(req.body) gives a "{}" value. Not sure why.
But console.log(data.toString()); in the dataservice gives the value of intended _id to be removed from MongoDb.
Try using data instead of data.toString() in
return this.http.post(URL, data.toString())
This will give you output value in console.log(req.body);
Also, try replacing the below line of code
collection.remove({_id: ObjectId(req.body.deleteId), function(err, result)
with
collection.deleteOne({_id: new mongodb.ObjectID(req.body.deleteId)}, function(err, result)
You need to create a new instance of mongodb here.
Hope this works.
I am trying to query my MongoDB to find all the matching name fields in the documents of my collection from the typeahead of my angular ui, I have to display the contents of the matched documents in table format, I referred few docs and wrote this API, when I try to test in Advanced REST client , it displays connection timed out, can anyone suggest me where I am going wrong?
My API code
var mongoose = require('mongoose');
var enterprise = mongoose.model('enterprise');
var search = function(req, res){
function searchEnterprise(){
var name = req.params.name;
enterprise.find({"name": '/^'+ name + '$/i'},function(err, data){
if (err){
console.log('err',err);
} else {
res.json(data);
console.log(data);
}
});
}
}
module.exports = {
searchEnterprise : search
};
no need nested function searchEnterprise(). just use it
var search = function(req, res){
var name = req.params.name;
// can also use $regex like bellow line
//enterprise.find({'name': {$options:'i', $regex: name }}, or
// enterprise.find({"name": '/'+ name + '/i'}
enterprise.find({'name': {$options:'i', $regex: name }},function(err, data){
if (err){
console.log('err',err);
return res.status(400).send({msg: "error"});
} else {
console.log(data);
return res.json(data);
// or
//return res.status(200).send(data);
}
});
};
module.exports = {
searchEnterprise : search
};
hi i am trying to remove a value from mongoDB but instead of removing a specific value the code is deleting all users from the schema lol.
var mongoose = require('mongoose');
var User = require('../../models/UserModel');
module.exports.unfollow = function(req, res){
var thefollowee = req.body.followee;
var thefollower = req.body.follower;
User.find({_id: thefollower}).remove({following: thefollowee}).exec();
User.find({_id: thefollowee}).remove({followers: thefollower}).exec();
res.json({ message: 'Unfollowed'});
};
the followee is pointing to the id of the person being followed,
the follower is pointing to the id of the user who follows the followee.
ok so i got it by using the $pull method
var mongoose = require('mongoose');
var User = require('../../models/UserModel');
module.exports.unfollow = function(req, res){
var thefollowee = req.body.followee;
var thefollower = req.body.follower;
User.findByIdAndUpdate(thefollowee, { $pull: { followers: req.body.follower }}, function (err, user) {
if (err)
return handleError(err);
});
User.findByIdAndUpdate(thefollower, { $pull: { following: req.body.followee }}, function (err, user) {
if (err)
return handleError(err);
});
res.json({ message: 'Unfollowed'});
};