gpt4 book ai didi

node.js - Mongoose 填充的问题

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:34 25 4
gpt4 key购买 nike

游戏架构

const { Schema, model } = require('mongoose');

const gameSchema = Schema({
_id: Schema.Types.ObjectId,
name: { type: String, required: true },
description: String,
calc: [{ type: Schema.Types.ObjectId, ref: 'Calc' }]
});

module.exports = model('Game', gameSchema);

计算架构

const { Schema, model } = require('mongoose');

const calcSchema = Schema({
_id: Schema.Types.ObjectId,
preset: { type: String, required: true },
datasets: [{ type: Schema.Types.ObjectId, ref: 'Dataset' }],
model: String,
});

module.exports = model('Calc', calcSchema, 'calc');

获取游戏路线

router.get('/', passport.authenticate('jwt', { session: false }), (req, res) => {
Game.find()
.select('_id name calc')
.populate('calc')
.then(games => res.status(200).json(games))
.catch(err => res.status(500).json({ error: err }));
});

calc 属性不是用 Calc 对象填充 calc 属性,而是替换 ids,而是变成空数组。如何正确使用填充?我的代码中是否犯了明显的错误?

简而言之:populate() 结果为 calc: [] 而不是 calc: [{Calc object}, ...]

最佳答案

在您的情况下,您正在尝试填充一组文档(而不仅仅是一个文档),因此您应该使用 Model.populate()方法代替。

Game.find()
.select('_id name calc')
.then(games => Game.populate(games, { path: 'calc' }))
.then(games => res.status(200).json(games))
.catch(err => res.status(500).json({ error: err }));

关于node.js - Mongoose 填充的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53969091/

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