gpt4 book ai didi

javascript - Mongoose.model ('model_name' ) 当 mongoose 模型模式文件中需要函数时返回空对象

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:23 26 4
gpt4 key购买 nike

如果问题的标题有误导性,我深表歉意,因为我不太确定如何解释这一点。我有 2 个文件,matchedTransaction.jsplayer.js

sharedApi/player.js

const MatchedTransactionModel = require('../models/matchedTransaction');

// #1: If I try to console log here, the output will be an empty object "{}"
console.log(MatchedTransactionModel);

async function banPlayer(userId) {
// ...
// Because MatchedTransactionModel is an empty object,
// the code below will crash with the following error:
// "MatchedTransactionModel.findOne is not a function"
const pendingMatchedTransaction = await MatchedTransactionModel.findOne({
$and: [
{
$or: [
{ reserverAccountId: `${account._id}` },
{ sellerAccountId: `${account._id}` },
],
},
{
$or: [
{ status: 'pendingReserverPayment' },
{ status: 'pendingSellerConfirmation' },
],
},
],
});
// ...
}

module.exports = {
banPlayer,
};

models/matchedTransaction.js

const mongoose = require('mongoose');
const { banPlayer } = require('../sharedApi/player');
const MatchedTransactionSchema = new mongoose.Schema([
{
createdDate: {
type: Date,
required: true,
},
// ...
},
]);

MatchedTransactionSchema.post('init', async function postInit() {
// ...
await banPlayer(userId);
});

const MatchedTransactionModel = mongoose.model('matchedTransactions', MatchedTransactionSchema);
module.exports = MatchedTransactionModel;

请注意,在 player.js 中,当我尝试 console.log 所需的 MatchedTransactionModel 时,它返回一个空对象。但是,如果我对 ma​​tchedTransaction.js 进行以下更改:

models/matchedTransaction.js

// Instead of requiring banPlayer outside, I only require it when it is used
// const { banPlayer } = require('../sharedApi/player');

MatchedTransactionSchema.post('init', async function postInit() {
// ...
const { banPlayer } = require('../sharedApi/player');
await banPlayer(userId);
});
// ...

前面提到的 console.log 的输出将是一个非空对象,并且 MatchedTransactionModel.findOne 正在按预期工作。

为什么会发生这种情况?

最佳答案

我在您的代码中看到的唯一问题是,当您在 matchedTransaction.js 上定义架构时,您传递了一个我认为有问题且没有意义的数组。您必须在那里传递一个对象:

const MatchedTransactionSchema = new mongoose.Schema({
createdDate: {
type: Date,
required: true,
},
// ...
});

关于javascript - Mongoose.model ('model_name' ) 当 mongoose 模型模式文件中需要函数时返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59855272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com