I have a datamodel named 'account' that stores a 'user'
var mongoose=require("mongoose");
mongoose.connect("mongodb://localhost/dataseed");
var db=mongoose.connection;
var accountSchema=mongoose.Schema({
user:{
type:mongoose.Schema.Types.ObjectId,
ref:"user"
},
accountholder:{
type:String
},
cvv:{
type:String
},
expiryyear:{
type:String
},
expirymonth:{
type:String
},
accountnumber:{
type:Number
},
currentamount:{
type:Number
},
transferedamount:{
type:Number
},
withdrawnamount:{
type:Number
}
});
var account = module.exports = mongoose.model('account', accountSchema);
When I'm trying to found an account using the account.find() function. However it returns undefined when I try to access account.accountnumber
I'm querying my model as follows:
data.findById({"_id":req.params.id},function(err,data){
console.log("DATA.USER --------------------------------------------------");
console.log(data.user);
if(err)console.log(err);
else{
acessToken.create({user:req.user,data:req.params.id,token:token},function(err,acess){
if(err)console.log(err);
else{
console.log("ACCESSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSss");
console.log(acess.user);
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
}
else
{
console.log("------------------------------------------------------------------------------------TYPE OF USER ID: " + typeof(req.user._id));
account.find({"user":req.user},function(err,d){
if(err)console.log(err)
var amount=d.currentamount-data.price;
var transferedamount=d.transferedamount+data.price;
console.log("Amount: "+amount); // NaN
account.findByIdAndUpdate({user:req.user},{currentamount:amount,transferedamount:transferedamount},function(err,update){
if(err)console.log(err);
console.log('Email sent: ' + info.response);
//getUsername of seller
// console.log(data.user)
user.findById({"_id":data.user},function(err,seller){
if(err){
console.log(err);
}else{
var buyer = req.user.username;
var seller = seller.username;
var priceOfData = data.price;
//ccNumber undefined
var ccnumber = d.accountnumber;
console.log("Buyer Name " +buyer);
console.log("Seller Name " +seller);
console.log("Price " +priceOfData);
console.log("Purchased on Credit Card Number " +ccnumber);
res.render('buyer/sold.ejs');
}
});
});
});
}
});
}
});
}
});
Models "data" and "acessToken" are used for finding a product and generating an access token of the purchased product.
This is the output im getting on my console.
5ca9ae4c044bab18588edf5b
ACCESSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSss
5cd4cc83c3c65514c61ae4f3
------------------------------------------------------------------------------------TYPE OF USER ID: object
Amount: NaN
{ CastError: Cast to ObjectId failed for value "{ user: 5cd4cc83c3c65514c61ae4f3 }" at path "_id" for model "account"
at MongooseError.CastError (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/error/cast.js:29:11)
at ObjectId.cast (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schema/objectid.js:232:11)
at ObjectId.SchemaType.applySetters (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:845:12)
at ObjectId.SchemaType._castForQuery (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:1248:15)
at ObjectId.SchemaType.castForQuery (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:1238:15)
at ObjectId.SchemaType.castForQueryWrapper (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:1217:15)
at cast (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/cast.js:252:34)
at Query.cast (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:4334:12)
at castQuery (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:4186:18)
at Query._findAndModify (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:3203:23)
at Query.<anonymous> (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:2830:8)
at Query._wrappedThunk [as _findOneAndUpdate] (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
at process.nextTick (/home/ubuntu/workspace/DataSeed/node_modules/kareem/index.js:369:33)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'Cast to ObjectId failed for value "{ user: 5cd4cc83c3c65514c61ae4f3 }" at path "_id" for model "account"',
name: 'CastError',
stringValue: '"{ user: 5cd4cc83c3c65514c61ae4f3 }"',
kind: 'ObjectId',
value: { user: 5cd4cc83c3c65514c61ae4f3 },
path: '_id',
reason: undefined,
model:
{ [Function: model]
hooks: Kareem { _pres: [Object], _posts: [Object] },
base:
Mongoose {
connections: [Object],
models: [Object],
modelSchemas: [Object],
options: [Object],
_pluralize: [Function: pluralize],
Schema: [Object],
model: [Function],
plugins: [Object] },
modelName: 'account',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
'$internalEmitter': [Object],
_listening: false,
_events: [Object],
_eventsCount: 1,
_connectionOptions: [Object],
name: 'dataseed',
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
client: [Object],
'$initialConnection': [Object],
db: [Object] },
discriminators: undefined,
events:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined },
'$appliedMethods': true,
'$appliedHooks': true,
_middleware: Kareem { _pres: [Object], _posts: [Object] },
schema:
Schema {
obj: [Object],
paths: [Object],
aliases: {},
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: [Object],
query: {},
childSchemas: [],
plugins: [Object],
'$id': 7,
s: [Object],
_userProvidedOptions: {},
options: [Object],
'$globalPluginsApplied': true,
_requiredpaths: [] },
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'accounts',
collectionName: 'accounts',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
'$init': Promise { [Object] },
'$caught': true } }
Email sent: 250 2.0.0 OK 1557500841 d4sm5108746wrv.42 - gsmtp
Buyer Name murtaza1
Seller Name test1
Price 100
Purchased on Credit Card Number undefined
The problem with your code is that when you query your database you also need to call the populate method exposed by MongoDB and in particular Mongoose which I'm assuming you're using to query the DB. More info on Mongoose docs.
Why this happens? Well, since you're declaring using as a reference to your account Schema when Mongoose query the DB it only returns, without the populate method, the ID of the document referenced by that particular account Schema. Hope this helps you, cheers, sigfried
Related
I am working with treemodel to create a tree representation
When I try to stringify it using json, or to string, I get an error of course.
What is the best way to stringify this tree model?
Here is example of my output
config:
{ childrenPropertyName: 'children',
modelComparatorFn: undefined },
model:
{ name: 0,
content:
{ questions: [Array],
results: [],
varName: 'Step #1',
attributes: [Array],
type: 'default',
contentElements: [] },
children:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ] },
children:
[ Node {
config: [Object],
model: [Object],
children: [],
parent: [Circular] },
I have the problem that when I make a post request to my schema it does not store the new values in the episodes array.
Using postman in the body I added the new data, I mean new anime content, but that content is not added to the array of episodes. In total there are 25 episodes but with the new content it is supposed to increase to 26.
Any help will be appreciated.
This is my body in POSTMAN
"url": "https: \ / \ / www.crunchyroll.com \ / 07-ghost \ / episode-26-the-heart-is-lead-by-the-truth-on-the-othe-side-578512 ",
"description": "Teito uses the power of the Eye of Mikhail to summon Frau, Castor, Labrador, Lance, and the Black Hawks.",
"episode_number": "26",
"thumbnail": "https: \ / \ / www.facebook.com \ / tr? id = 2107366626037622 & ev = PageView & noscript = 1",
"name": "07 Ghost Episode 26"
}
Schema
"episodes": {
"1x": {
"07 Ghost": [{
"url": "https:\/\/www.crunchyroll.com\/07-ghost\/episode-25-the-heart-is-lead-by-the-truth-on-the-other-side-578512",
"description": "Teito uses the power of the Eye of Mikhail to summon Frau, Castor, Labrador, Lance, and the Black Hawks.",
"episode_number": "25",
"thumbnail": "https:\/\/www.facebook.com\/tr?id=2107366626037622&ev=PageView&noscript=1",
"name": "07 Ghost Episode 25"
},
POST REQUEST
// Update the "Episodes" array in the DB when a JSON is sent via "POST" request.
router.post('/series/:id/post' , (req , res , next) =>{
let id = req.params.id;
SeriesModel.findOneAndUpdate({
_id: new ObjectID(id)
},{
$push: {
"episodes.${'1x'}.${'07 Ghost'}": {
"url": req.body.url,
"description": req.body.description,
"episode_number": req.body.episode_number,
"thumbnail": req.body.thumbnail,
"name": req.body.name,
}
}
},
{new: true}, (err, result) => {
if(err){
console.error('error to update episodes')
}else{
console.log("episode section updated" , result)
}
}).then(result =>{
console.log(result);
res.status(200).json({
message: "Handling POST request to episodes",
episode: result
})
}).catch(err =>{
res.status(500).json({error: err})
})
})
This is the output after POST REQUEST in the terminal
POST /api/v1/animes/series/5d454473084e0306452caa12/post 200 929.910 ms - 19844
[nodemon] restarting due to changes...
[nodemon] starting `node src/index.js`
�🚀 Listening: http://localhost:8081
episode section updated { aggregateRating:
{ reviewCount: 100,
ratingCount: 1387,
'#type': 'AggregateRating',
ratingValue: 4.7 },
episodes: { '1x': { '07 Ghost': [Array] } },
metadata:
{ description:
'Teased unmercifully for his past as an orphan and a slave, Teito has only his best friend Mikage and his mastery of the magical art of Zaiphon to ease his days at the elite Barsburg Academy.',
url: 'http://www.crunchyroll.com/07-ghost',
image:
'https://img1.ak.crunchyroll.com/i/spire4/1d3f1855ba933617b4d6792d9d3154191300831088_full.jpg',
type: 'TVSeries',
id: 'http://www.crunchyroll.com/07-ghost',
name: '07 Ghost' },
'1x':
{ '07 Ghost':
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ] },
_id: 5d454473084e0306452caa12,
series_id: 'GYWE4X28Y',
__v: 0 }
POST /api/v1/animes/series/5d454473084e0306452caa12/post 200 740.518 ms - 19844
[nodemon] restarting due to changes...
[nodemon] starting `node src/index.js`
�🚀 Listening: http://localhost:8081
episode section updated { aggregateRating:
{ reviewCount: 100,
ratingCount: 1387,
'#type': 'AggregateRating',
ratingValue: 4.7 },
episodes: { '1x': { '07 Ghost': [Array] } },
metadata:
{ description:
'Teased unmercifully for his past as an orphan and a slave, Teito has only his best friend Mikage and his mastery of the magical art of Zaiphon to ease his days at the elite Barsburg Academy.',
url: 'http://www.crunchyroll.com/07-ghost',
image:
'https://img1.ak.crunchyroll.com/i/spire4/1d3f1855ba933617b4d6792d9d3154191300831088_full.jpg',
type: 'TVSeries',
id: 'http://www.crunchyroll.com/07-ghost',
name: '07 Ghost' },
'1x':
{ '07 Ghost':
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ] },
_id: 5d454473084e0306452caa12,
series_id: 'GYWE4X28Y',
__v: 0 }
According to postman the update was successful
"message": "Handling POST request to episodes"
You can see in the episode arrangement, continue with the 25 episodes and not with 26 that is supposed to happen.
This question already has answers here:
mongoose .find() method returns object with unwanted properties
(5 answers)
How can I display a JavaScript object?
(40 answers)
Closed 4 years ago.
I made a simple find query for mongoose, and it returns the result as well but it gives result in array of objects(this is not a problem), but it have array of objects, with objects contains its internal functions and properties, which I think not relevant to my need, as I only want the query result from database.
const Joi = require('joi');
const Session = require('../models/session.model');
exports.tokenUtility = async (req, res, next) => {
const {token, contactNumber, query} = req.body;
if(token) {
try{
const session = await Session.find({token});
console.log("Found Session", session);
} catch(error) {
next(error)
}
} else {
console.log("in token util, token is not present");
const generatedToken = (Math.random()*1e18).toString(36);
}
}
It gives me this result from output of Found Session
Found Session [ model {
'$__':
InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
saving: undefined,
version: undefined,
getters: {},
_id: 5ae31a2062728504f78ee860,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths:
StateMachine {
paths:
{ token: 'init',
context: 'init',
contextArray: 'init',
_id: 'init',
__v: 'init' },
states:
{ ignore: {},
default: {},
init:
{ _id: true,
context: true,
contextArray: true,
token: true,
__v: true },
modify: {},
require: {} },
stateNames: [ 'require', 'modify', 'init', 'default', 'ignore' ] },
pathsToScopes: {},
session: null,
ownerDocument: undefined,
fullPath: undefined,
emitter:
EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: 0 },
'$options':
{ skipId: true,
isNew: false,
skipDefaults:
{ _id: true,
context: true,
contextArray: true,
token: true,
__v: true } } },
isNew: false,
errors: undefined,
_doc:
{ context: 'client',
contextArray:
[ toBSON: [Function: toBSON],
_atomics: {},
_parent: [Circular],
_cast: [Function: _cast],
_markModified: [Function: _markModified],
_registerAtomic: [Function: _registerAtomic],
'$__getAtomics': [Function: $__getAtomics],
hasAtomics: [Function: hasAtomics],
_mapCast: [Function: _mapCast],
push: [Function: push],
nonAtomicPush: [Function: nonAtomicPush],
'$pop': [Function: $pop],
pop: [Function: pop],
'$shift': [Function: $shift],
shift: [Function: shift],
pull: [Function: pull],
splice: [Function: splice],
unshift: [Function: unshift],
sort: [Function: sort],
addToSet: [Function: addToSet],
set: [Function: set],
toObject: [Function: toObject],
inspect: [Function: inspect],
indexOf: [Function: indexOf],
remove: [Function: pull],
_path: 'contextArray',
isMongooseArray: true,
validators: [],
_schema: SchemaArray {
casterConstructor: { [Function: SchemaString] schemaName: 'String' },
caster:
SchemaString {
enumValues: [],
regExp: null,
path: 'contextArray',
instance: 'String',
validators:
[ { validator: [Function],
message: 'Path `{PATH}` is required.',
type: 'required' } ],
setters: [],
getters: [],
options: { required: true },
_index: null,
isRequired: true,
requiredValidator: [Function],
originalRequiredValue: true },
'$isMongooseArray': true,
path: 'contextArray',
instance: 'Array',
validators: [],
setters: [],
getters: [],
options: { type: [ { type: [Function: String], required: true } ] },
_index: null,
defaultValue: { [Function: defaultFn] '$runBeforeSetters': true } } ],
_id: 5ae31a2062728504f78ee860,
token: '3agcnp5ufl8g',
__v: 0 },
'$init': true } ]
The bootcamp I went to taught postgres using the knex/bookshelf libraries, but at the moment I don't know how to use the reqular queries(ie. SELECT FROM etc...).
I've haven't tried a relational query with the knex/bookshelf libraries until now and I can't get it to work. I've looked at the documentation and as far as I can tell I've used the syntax they say to.
exports.getStudentsByClass = (key) => {
return Classroom.where({ id: key }).fetch({
withRelated: 'student'
})
.then(classroom => {
const students = classroom.related('student')
console.log(classroom.models.map(student => {
studentList.attributes
}))
return classroom
})
.catch(err => {
console.log(err)
})
}
This is the function I am using to query the database. When I console log the data this is what I get
CollectionBase {
model:
{ [Function]
super_: [Function: Events],
extend: [Function: extend],
extended: [Function: extended],
__super__:
ModelBase {
_builder: [Function: builderFn],
_relation: [Function: _relation],
Collection: [Object] },
NotFoundError: [Function: ErrorCtor],
NoRowsUpdatedError: [Function: ErrorCtor],
NoRowsDeletedError: [Function: ErrorCtor],
forge: [Function: forge],
collection: [Function: collection],
count: [Function: count],
fetchAll: [Function: fetchAll],
where: [Function],
query: [Function] },
length: 5,
models:
[ ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c77',
id: 7 },
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c78',
id: 4 },
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c79',
id: 9 },
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c80',
id: 14 },
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c81',
id: 10 } ],
_byId:
{ '4':
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c78',
id: 4 },
'7':
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c77',
id: 7 },
'9':
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c79',
id: 9 },
'10':
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c81',
id: 10 },
'14':
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c80',
id: 14 },
c77:
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c77',
id: 7 },
c78:
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c78',
id: 4 },
c79:
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c79',
id: 9 },
c80:
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c80',
id: 14 },
c81:
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c81',
id: 10 } },
relatedData:
RelationBase {
targetTableName: 'student',
targetIdAttribute: 'id',
type: 'hasMany',
target:
{ [Function]
super_: [Function: Events],
extend: [Function: extend],
extended: [Function: extended],
__super__: [Object],
NotFoundError: [Function: ErrorCtor],
NoRowsUpdatedError: [Function: ErrorCtor],
NoRowsDeletedError: [Function: ErrorCtor],
forge: [Function: forge],
collection: [Function: collection],
count: [Function: count],
fetchAll: [Function: fetchAll],
where: [Function],
query: [Function] },
foreignKey: 'classroom_id',
foreignKeyTarget: undefined,
parentId: 6,
parentTableName: 'classroom',
parentIdAttribute: 'id',
parentAttributes:
{ id: 6,
created_at: 2018-04-24T22:23:34.819Z,
updated_at: 2018-04-24T22:23:34.819Z,
name: ' Classroom 1' },
parentFk: 6 } }
So I'm not sure how to make this work
I used mongo-nodejs 2.2 and upgraded to 3.0. After upgrading, I found that the method db() in Db class doesn't exist anymore (http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html). This method is very useful to switch to different database instance. I wonder how I can switch to different database with the latest version.
Okay so it is gone, and it's documented as gone and the real message is you should be using Mongoclient.prototype.db instead:
From the 3.0 Changes:
We removed the following API methods.
Db.prototype.authenticate
Db.prototype.logout
Db.prototype.open
Db.prototype.db
...
We've added the following API methods.
MongoClient.prototype.logout
MongoClient.prototype.isConnected
MongoClient.prototype.db
The basic lesson here was wherever you were using Db directly, you should be using the MongoClient instance instead. This is obtained from the very first connection:
const { MongoClient } = require('mongodb');
(async function() {
try {
const conn = await MongoClient.connect('mongodb://localhost');
let test = conn.db('test');
let admin = test.admin();
console.log(admin);
let another = conn.db('another');
console.log(another);
} catch(e) {
console.error(e);
} finally {
process.exit();
}
})()
Returns output like:
Admin {
s:
{ db:
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
promiseLibrary: [Function: Promise] } }
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ databaseName: 'another',
dbCache: {},
children: [],
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
options:
{ readPreference: [Object],
promiseLibrary: [Function: Promise] },
logger: Logger { className: 'Db' },
bson: BSON {},
readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] }
Interestingly the admin() helper still exists on Db instances, which of course is really just a "pre filled" selection to the old db() anyway.
Bottom line, use the MongoClient instance from the connection instead for all future code.