gpt4 book ai didi

javascript - Node Express Mongoose 数组未填充引用模型

转载 作者:可可西里 更新时间:2023-11-01 09:28:47 24 4
gpt4 key购买 nike

我一直在尝试在模型数组中添加相关模型。但是当我测试 api 时,数组总是空的。我一直在 Stackoverflow 和谷歌中寻找答案,但没有任何效果。

模式和模型

let UserSchema = new Schema({
title: { type: String, required: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
username: { type: String, required: true, unique: true },
avatar: String,
email: { type: String, required: true },
dob: String,
password: { type: String, required: true },
createdAt: Date,
accounts: [{ type: Schema.Types.ObjectId, ref: 'Account' }] // --> this is what I want to fill
});

let AccountSchema = new Schema({
createdAt: Date,
accountNumber: { type: Number, required: true },
balance: Number,
daysLeft: Number,
nextMonthPayment: Number,
paymentType: String,
currentPlan: {
name: { type: String, required: true },
usage: {
used: Number,
left: Number,
total: Number,
meta: {
trafficData: [{
date: Date,
amount: Number,
download: Number,
upload: Number
}],
}
}
},
user: { type: Schema.Types.ObjectId, ref: 'User' }
});

User = mongoose.model('User', UserSchema);
Account = mongoose.model('Account', AccountSchema);
// end: SCHEMAS & MODELS

处理中

// POST
router.post('/accounts', (req, res) => {
user = new User({
title: 'Ms',
firstName: 'Paula',
lastName: 'Testerson',
username: '@paulatest',
avatar: '',
email: 'paula.test@emailtest.com',
dob: '01 January 1989',
password: 'test123',
createdAt: Date.now()
});

account = new Account({
createdAt: Date.now(),
accountNumber: 7651234,
balance: 91.75,
daysLeft: 23,
nextMonthPayment: 19.57,
paymentType: 'debit card',
currentPlan: {
name: 'Fast Furious',
usage: {
used: 10356,
left: 89644,
total: 100000,
meta: {
trafficData: [{
date: 'Fri Dec 22 2017 14:42:14 GMT+0000 (GMT)',
amount: 100.50,
download: 20.65,
upload: 16.90
}],
}
}
},
user: user._id
});

user.save((err) => {
if (err) { res.send(err); }

account.save(err => {
if (err) { res.send(err); }
res.json({
message: 'Account created!',
status: 'created'
});
});

user.find({})
.populate('accounts') // --> this is not working somehow
.exec()
.then((users) => {
console.log('User - ', users);
})
.catch(err => {
console.log('User err - ', err);
});
});
});

// GET
router.get('/', (req, res) => {
res.json({ message: 'Welcome to accounts api' });
});

router.get('/accounts', (req, res) => {
Account.find((err, accounts) => {
if (err) { res.send(err); }
res.json(accounts);
});
});

router.get('/users', (req, res) => {
User.find({})
.populate('accounts') // --> this is not working somehow
.exec((err, users) => {
if (err) { res.send(err); }
res.json(users);
});
});

这就是我到目前为止所做的,但 User.accounts 仍未填充。解决方案是什么?

最佳答案

您的问题的解决方案定义如下:

router.post('/accounts', (req, res) => {
user = new User({
title: 'Ms',
firstName: 'Paula',
lastName: 'Testerson',
username: '@paulatest',
avatar: '',
email: 'paula.test@emailtest.com',
dob: '01 January 1989',
password: 'test123',
createdAt: Date.now()
});

account = new Account({
createdAt: Date.now(),
accountNumber: 7651234,
balance: 91.75,
daysLeft: 23,
nextMonthPayment: 19.57,
paymentType: 'debit card',
currentPlan: {
name: 'Fast Furious',
usage: {
used: 10356,
left: 89644,
total: 100000,
meta: {
trafficData: [{
date: 'Fri Dec 22 2017 14:42:14 GMT+0000 (GMT)',
amount: 100.50,
download: 20.65,
upload: 16.90
}],
}
}
},
user: user._id
});

user.accounts.push(account._id); // you have to pushed the account id into newly created user doc
user.save((err, savedUser) => {
if (err) {
res.send(err);
}

account.save(err => {
if (err) {
res.send(err);
}

// It is better approach to use populate rather than finding the user by using .find() method
User.populate(savedUser, {
path: 'accounts'
}, (err, populatedUser) => {
if (err) {
res.send(err);
}
console.log(populatedUser);

// send response here //

});
});
});
});

建议:最好建立一个关系,在您的情况下,您在用户模型中引用帐户,在帐户模型中引用用户,这意味着双重引用。因此,要处理此问题,您应该在帐户模型中引用用户或在用户模型中引用帐户,而不是同时引用两者。

关于javascript - Node Express Mongoose 数组未填充引用模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48457535/

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