Findone Mongoose

Using GraphQL Variables - Schema Issues - 'Syntax Error: Expected Name, found "$".'

2020.06.15 18:55 theone85ca Using GraphQL Variables - Schema Issues - 'Syntax Error: Expected Name, found "$".'

Hey All,
Hoping someone can help me out. Like many I'm getting started down the rabbit hole with GraphQL and I'm running in to some issues with variables.
const { buildSchema } = require('graphql'); var Int32 = require('mongoose-int32'); module.exports = buildSchema(` type Query { listSubClass ($name: String){ Subclasses (index: $name) { index: String name: String } } } `); 
I've stripped things down a little but the above code generates the error. 'Syntax Error: Expected Name, found "$".'
I'm expecting to be able to pass a variable to this query and then have mongoose use that to findOne in MongoDB.
What am I missing when defining variables in a query?
submitted by theone85ca to graphql [link] [comments]


2020.04.12 18:50 EddiesTech MongoDB Mongoose findOne as variable

[SOLVED] Hi there,
I am a complete noob to all this Mongoose stuff, but I was told it will save me more time in the future. I have this code: http://codebin.herokuapp.com?s=5e9321dde8e7270004000001 I was wondering if there was a way I can make the value returned a variable. I have the code just return the 'xp' value, but it comes up like this: {xp: 0} when I just want the 0 so I can save it as a variable and do maths on it. How can I do this?
Any help would be appreciated, Eddie
submitted by EddiesTech to learnjavascript [link] [comments]


2020.04.12 16:14 EddiesTech MongoDB Mongoose findOne as variable

[SOLVED]
Hi there,
I am a complete noob to all this Mongoose stuff, but I was told it will save me more time in the future. I have this code: http://codebin.herokuapp.com?s=5e9321dde8e7270004000001I was wondering if there was a way I can make the value returned a variable. I have the code just return the 'xp' value, but it comes up like this: {xp: 0} when I just want the 0 so I can save it as a variable and do maths on it. How can I do this?
Any help would be appreciated,Eddie
submitted by EddiesTech to Discord_Bots [link] [comments]


2020.03.24 16:50 weaponizedLego ReferenceError: Cannot access 'user' before initialization

I have this error that I can't really figure out why I am getting. I use mongoose to model my db models, and I try to use findOne on a collection but I get this error
ReferenceError: Cannot access 'user' before initialization 
on line 49 of the pastebin below
here is the entire file. pastebin link
I don't get how I can get a refference error on the same line I'm declaring the damn thing.
submitted by weaponizedLego to learnjavascript [link] [comments]


2020.03.22 13:19 radioactive-poop Needed some advice .

I'm sory if this is a noob question but I'm new to node js. I'm trying to build a rest API and it involves the use of mongoose. I have three primary Models in place :
A User model
A "Tank" model with foreign key referencing the _id of the User Model
A "Usage" model with foreign key referencing the "label" (unique) of the Tank.
So each User-Tank-Usage is unique.
In the "post" method for usage, I have specified a route as : /tank/:label/usage for adding a new entry to the usage collection. Now I want a way to ensure that the post method only goes through if the tank with that label exists. I wanted to know what's a better way to do this:
1) Use some middleware that checks the Tank model using findOne each time.
2) Use the "GET /tanks/:label" path I have already defined in the tank routes (is there some way to ping and check response?)
Thanks!
submitted by radioactive-poop to node [link] [comments]


2020.01.11 11:44 kszyh_pl mongoose - fields filtering

Hi,
In most cases I am creating method in Mongoose schema which is responsible for filtering what is returned to the user. It usually looks like this:
MySchema.methods = { view (full) { const view = { // simple view id: this.id, title: this.title, createdAt: this.createdAt, updatedAt: this.updatedAt, } return full ? { ...view, other: this.other, other2: this.other2, } : view } } 
This works fine if data is fetched using find or findOne methods, but does not work for aggregation. AFAIK results obtained from aggregation does not have access to "methods".
How do you handle fields filtering? Do you write separate / stand-alone methods, use fields selection in the query, or is there any smarter approach? My apps are primarily based on express.
submitted by kszyh_pl to node [link] [comments]


2019.12.11 07:55 dejavits Mongoose FindOne extremely slow!

Hello all,
I have realized that the following code related to the registration of an user takes around 4 seconds, is that normal? Even during testing where I have only one user it takes that long.
javascript if (password === repeatedPassword) { try { const existingUser = await User.findOne({ 'local.email': email }); if (existingUser) { if (existingUser.local.registrationConfirmed) { return res.status(400).send({ type: errorTypes.REGISTER_ERROR_VERIFIED_USER_EXISTS_ALREADY, payload: req.t(`auth:${errorTypes.REGISTER_ERROR_VERIFIED_USER_EXISTS_ALREADY}`) }); } return res.status(400).send({ type: errorTypes.REGISTER_ERROR_NON_VERIFIED_USER_EXISTS_ALREADY, payload: req.t(`auth:${errorTypes.REGISTER_ERROR_NON_VERIFIED_USER_EXISTS_ALREADY}`) }); }
My schema is as follows:
```javascript
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({ local: { type: { email: { type: String, unique: true, required: true }, name: { type: String, required: true }, password: { type: String, required: true }, resetPasswordToken: String, resetPasswordExpires: Date, verificationToken: String, verificationExpires: { type: Date, default: () => new Date(+new Date() + 7 * 24 * 60 * 60 * 1000) }, registrationConfirmed: { type: Boolean, default: false } }, required: false }, google: { id: String, name: String, email: String }, accountType: String });
userSchema.index( { 'local.verificationExpires': 1 }, { name: 'Remove unverified users', expireAfterSeconds: 3600, partialFilterExpression: { 'local.registrationConfirmed': false } } );
module.exports = mongoose.model('User', userSchema); ```

Could the index I create be the problem? Is there a way to improve things? or is this expected?
Thank you in advance and regards.
submitted by dejavits to node [link] [comments]


2019.03.27 14:26 CyrilZN FindOne error when creating new Model Mongoose

Hi there

I try to create a new User linked with a profile. Here is my models :

UserModel :

import mongoose from 'mongoose'; import {RoleModel} from "./RoleModel"; const bcrypt = require('bcrypt'); const UserSchema = new mongoose.Schema({ username: { type: String, required: true }, firstname: { type: String, required: true }, lastname: { type: String, required: true }, email: { type: String, required: true }, mobile: { type: String, required: () => { return !(!this.phone) } }, phone: { type: String, required: () => { return !(!this.mobile) } }, role: { type: mongoose.Schema.Types.ObjectId, ref: RoleModel, required: true }, password: { type: String, required: true } }, { validateBeforeSave: true, timestamps: true }); UserSchema.methods.validPassword = async (password, user) => { try { return await bcrypt.compare(password, user.password); } catch (err) { await Promise.reject(new Error('Error during authentication')); } }; export const UserModel = mongoose.model("users", UserSchema); 

RoleModel :

import mongoose from 'mongoose'; const RoleSchema = new mongoose.Schema({ name: { type: String, required: true } }, { validateBeforeSave: true, timestamps: true }); export const RoleModel = mongoose.model("role", RoleSchema); 


With them I try to insert a new User and getting a role by name in creation. Unfortunately, I always get a `Segmentation fault (core dumped)` or Error during save. It seems my role is not found before saving action.

Here my methods :
import {UserModel} from "./Model/UserModel"; import mongoose from "mongoose"; const bcrypt = require('bcrypt'); let user = new UserModel({ username: 'Fubar', firstname: 'Foo', lastname: 'Bar', email: '[email protected]', mobile: 'my-awesome-mobile', role: RoleModel.findOne({name: 'DEFAULT_ROLE'}, (err, role) => { if (err) return handleError(err); return role; }), password: bcrypt.hash('myPlaintextPassword', 15, (err, hash) => { if (err) return handleError(err); return hash; }); }); user.save(err => { if (err) return handleError(err); }); 

Could you help me to reach to save efficiently my user please ? I guess I misunderstood something, but despite of my tests, I did not succeed to point it out..

Thanks,
submitted by CyrilZN to node [link] [comments]


2018.09.12 18:32 lc929 Is there a way to load data synchronously from mongodb within my NodeJS app upon bootup?

I have a service configured that calls data from my database upon booting up my NodeJS server. The problem is, since the findOne calls (with mongoose) are asynchronous, it doesn't return the objects in time, so I'm left with empty objects. Is there a way to load this data synchronously?

Thanks
submitted by lc929 to node [link] [comments]


2018.08.18 20:28 atacamasand How to _update_ Mongo object inside array if object exists, add it to array if it doesn't?

I'm learning Mongo and I've encountered a tricky problem. It's for a class, so although this might be easier with Mongoose (or may not), we're supposed to do it with Mongo.
I'm making a simple app to handle contacts for a variety of users. The collection will have an array of various users, each of which will have an array of contacts, and those contact arrays will contain an array of objects with various strings.
 users: [ user: { contacts: [ contact: { name:"a string" } ] } ] 
What I want to do is to have a function updateContact to which I will pass the username and a contact object. The function will add a contact to a user's contacts array if and only if there is no match on the name field for that contact, but if there is a match on the name field will update the information in the matched contact object.
I can figure out how to add the new contact but not how to check if it exists in the array and perform a merge in that case.
I have
 return this._users.findOne({username}) .then(user => { if (!user) throw new LogicError(`user ${username} does not exist`) return this._users.updateOne( user, {$push: {"contacts": contact}} ) }) 
My thought was to do a check first with findOne to see if the contact already exists in the array, and only add it with the above code if it is missing, but I don't know how to handle the case when it doesn't exist -- that is, if I'm using Promises, do I put the "add" code above in a catch?
I feel sure there must be a way to solve this issue. Any help much appreciated!
submitted by atacamasand to mongodb [link] [comments]


2018.02.05 08:36 epic_within Mongoose .findOne returns document first, and then NULL

When going to the user route, first it returns the document. Again(I don't restart), it returns null. Here's the code:
 app.get("/autho:name", function(req,res,next) { Article.find({ author : req.params.name}).sort([['_id', -1]]).exec(function(err,allArticle) { // find all documents associated with the name if(err) { console.log(err); next(); } else { res.locals.article = allArticle; next(); } }) }, function(req,res) { User.findOne({username : req.params.name}, function(err,user) { if(err) { // find user with the name in the route console.log(err); } else { console.log(user); res.locals.name = req.params.name; res.locals.user = user; res.locals.title = req.params.name + " OtakuPort"; res.locals.user.bio = marked( user.bio ); res.render("showAuthor", res.locals); } }) }) 
Output
Not sure why this weird behavior is happening, ONLY ON THIS ROUTE!
It'd be great if anyone can help me with this.
Thanks!
submitted by epic_within to node [link] [comments]


2017.07.01 13:09 thelynched mlab and Heroku interprating findByAndUpdate as findOne

Hi there,
so I'm making a node.js aplication with a REST API but when I send a put request the debug outputs this:
2017-07-01T11:03:43.467415+00:00 app[web.1]: [0;36mMongoose:[0m users.findOne({ _id: ObjectId("adfsadfasdfsadfsadfasfdasda23ffa344") }, { new: [33mtrue[39m, fields: {} }) 2017-07-01T11:03:43.482159+00:00 app[web.1]: [0;36mMongoose:[0m users.findOne({ _id: ObjectId("adfsadfasdfsadfsadfasfdasda23ffa344") }, { fields: {} }) 
Which is odd as the code is this:
router.put('/use:id', function(req, res, next){ User.findByIdAndUpdate({_id: req.params.id}, req.body, {new: true}).then(function(){ User.findOne({_id: req.params.id}).then(function(user){ res.send(user); }); }).catch((err) => console.error(err)); }); 
So it appears the findByandUpdate is been run as findOne which leads to the data in the db not updating. Any ideas? Thanks in advance, Ed.
submitted by thelynched to webdev [link] [comments]


2017.03.27 00:46 ImtheDr check for a document on DB using mongoose

I'm looking for a way to check if a document already exist on my DB by checking one of the document's properties.
The problem is, findOne doesn't return a Boolean, right?
so...
How can I get a Boolean value to put on an if/else statement using mongoose?
thanks!
submitted by ImtheDr to learnjavascript [link] [comments]


2017.01.01 01:23 Lukeg1337 Mongoose $and search query

hey, this is my schema in mongoose (basically translatable parameterValue):
var mongoose = require('mongoose'), Schema = mongoose.Schema, findOrCreate = require('mongoose-findorcreate'); var parameterValueSchema = new mongoose.Schema({ _parameter: {type: Schema.Types.ObjectId, ref: 'Parameter'}, name: [{ _lang: { type: Schema.Types.ObjectId, ref: 'Language' }, value: String }], created: {type: Date, default: Date.now}, state: {type: String, enum: ['E','P'], default: 'E'} }); parameterValueSchema.plugin(findOrCreate); var ParameterValue = mongoose.model('ParameterValue', parameterValueSchema); exports.parameterValue = ParameterValue; 
and this is my 'where' part of the findOne query:
{ $and: [{ 'name._lang': {$in: [languageId]} }, { 'name.value': valueName }, { '_parameter': parameterId }] } 
which doesn't return correct results, while this search query on a bit different schema (same, only without _parameter attr.):
{ $and: [{ 'name._lang': {$in: [languageId]} }, { 'name.value': name }] } 
does - can you guys tell me what am I doing wrong ?
In the 1st search query I'm basically trying to get all parameter values with certain parameter id and name of the parameterValue in certain language
submitted by Lukeg1337 to mongodb [link] [comments]


2016.12.01 23:13 manfromixtlan Having Problems with FindOne function in controller.

Hello world
I am trying to write a MEAN stack program using mongoose to check if user input (address as string) is already in a collection (addresses as strings). I thought this would be straight forward but I can't seem to wire it up right. I have looked up a couple ideas but nothing that fits my needs. I have previous been able to find public or private existing API's and check my data with there's sending a POST from angular. However, our dataset is unique so I need to build a searchable collection in mongodb and check if the user input exists to display validation to the user. I started writing a number of findOne functions in my node controller but as I get further I feel like I have less idea what I am doing. Any ideas would be very much appreciated.
submitted by manfromixtlan to node [link] [comments]


2014.04.20 00:00 tigerCode Weird mongoose and mongo error, mongoose.connection.host returns null

So I been debugging this weird error in which saving and findone does not work, overtime I suspect the connection is not right so I did a print out
console.log(mongoose.connection.host); console.log(mongoose.connection.port); 
In which both returns null
This is especially confusing when
mongoose.createConnection(connStr, function(err){ if (err) throw err; console.log ('Successfully connected to MongoDB'); console.log(mongoose.connection.host); console.log(mongoose.connection.port); }); 
There are no errors throwed?
Why is this happening, and how do I fix it?
Thanks
submitted by tigerCode to learnprogramming [link] [comments]


2014.04.15 00:39 aweggwe How do I access an object from aggregate using mongoose in node.js?

Hi, I been having trouble with aggregate using mongodb and mongoose, I tried find, findone, indexing everything seems to return nothing
db.collection.aggregate([]) 
Any advice would be appreciated
submitted by aweggwe to nodejs [link] [comments]


A Mongoose and Black Mamba Fight to the Death - YouTube The MongoDB findOne() Function Mongoose Aggregate Find and Sum Example (Mongoose Tutorial) Mongoose Vs. Cobra - YouTube Use mongoose and Express to Find one User using Id from the MongoDB Using mongoose - Querying Collections using find or findOne MongoDb Tutorial 8 : How to you findOne() in mongoDb Mongoose Schemas & Models

  1. A Mongoose and Black Mamba Fight to the Death - YouTube
  2. The MongoDB findOne() Function
  3. Mongoose Aggregate Find and Sum Example (Mongoose Tutorial)
  4. Mongoose Vs. Cobra - YouTube
  5. Use mongoose and Express to Find one User using Id from the MongoDB
  6. Using mongoose - Querying Collections using find or findOne
  7. MongoDb Tutorial 8 : How to you findOne() in mongoDb
  8. Mongoose Schemas & Models

Using mongoose - Querying Collections using find or findOne itversity. Loading... Unsubscribe from itversity? ... #1 Mongoose - deep collections connect with populate - Duration: 16:09. Simple login using Mongoose / MongoDB - Node.js Tutorial 17 - Duration: 9:35. Manthan Dave 78,567 views. 9:35. 12 Year Old Boy Humiliates Simon Cowell - Duration: 5:37. Course: Angular 2 and NodeJS - The Practical Guide to MEAN Stack 2.0 Buy the full course here: https://bit.ly/33Nmyuu. Calling the findOne() function on a specific collection, passing over a criteria, we will get all documents that fit the critera we pass. This short video clip explains this function. A mongoose is lightning fast and has razor-sharp teeth. A black mamba can kill 15 grown men with just one bite. Which of these two mortal enemies will win? W... sample file download link : https://github.com/premaseem/MongoCertification2016/blob/master/scripts/sampleHotelData.json # Command to import sample data MQ42... Mongoose and MongoDB support aggregate functions, for example getting the sum of a column in a 'table'. We also do a find query with our Mongoose sum query to only get links from a certain user. Mongooses and snakes are each other's deadliest opponents. When they face off, the outcome is utterly unpredictable. Watch the Full Episode with your FREE tr...