问题
我有一个名为“account”的数据模型。它存储了一个“用户”。
- 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 时,它返回 undefined
我正在像这样查询我的模型:
- 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');
- }
- });
- });
- });
- }
- });
- }
- });
- }
- });
复制代码
模型“数据”和“accessToken”用于查找产品并生成访问令牌以购买产品。
这是我在控制台上得到的输出。
- 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
复制代码
回答
您的代码的问题在于,当您查询数据库时,您还需要调用 populate 公开的 MongoDB 方法,特别是 Mongoose 方法,我假设您使用它来查询数据库。有关猫鼬文档的更多信息。
为什么会这样?好吧,因为您声明使用 as account Schema 来引用您的引用,所以当 Mongoose 查询数据库时,它只返回该特定填充引用的文档的 ID,而不是 account Schema 方法。希望这对你有帮助,干杯齐格弗里德
|