MongoDB 未找到数据:returns 未定义
MongoDB Not Finding Data : returns undefined
我有一个名为 'account' 的数据模型,它存储 '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);
当我尝试使用 account.find()
函数查找帐户时。但是,当我尝试访问 account.accountnumber
时,它 returns 未定义
我正在查询我的模型如下:
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');
}
});
});
});
}
});
}
});
}
});
模型 "data" 和 "acessToken" 用于查找产品并生成购买产品的访问令牌。
这是我在控制台上得到的输出。
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
你的代码的问题是,当你查询你的数据库时,你还需要调用 MongoDB
公开的 populate
方法,特别是 Mongoose
我假设你用于查询数据库。有关 Mongoose docs 的更多信息。
为什么会这样?好吧,因为当 Mongoose
查询数据库时,您声明 using as a reference
to your account Schema
它只 returns,没有 populate
方法,ID
该特定 account Schema
引用的文档。希望这对你有帮助,干杯,sigfried
我有一个名为 'account' 的数据模型,它存储 '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);
当我尝试使用 account.find()
函数查找帐户时。但是,当我尝试访问 account.accountnumber
我正在查询我的模型如下:
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');
}
});
});
});
}
});
}
});
}
});
模型 "data" 和 "acessToken" 用于查找产品并生成购买产品的访问令牌。
这是我在控制台上得到的输出。
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
你的代码的问题是,当你查询你的数据库时,你还需要调用 MongoDB
公开的 populate
方法,特别是 Mongoose
我假设你用于查询数据库。有关 Mongoose docs 的更多信息。
为什么会这样?好吧,因为当 Mongoose
查询数据库时,您声明 using as a reference
to your account Schema
它只 returns,没有 populate
方法,ID
该特定 account Schema
引用的文档。希望这对你有帮助,干杯,sigfried