gpt4 book ai didi

node.js - Mongoose findById 没有返回所有字段

转载 作者:行者123 更新时间:2023-12-03 12:17:46 24 4
gpt4 key购买 nike

我正在使用 mongoose 调用 findById,它没有返回所有字段,或者至少没有正确映射到字段。但如果我使用聚合,它会返回该字段

我有以下架构

const ratingSchema = new mongoose.Schema({
rating: {
type: Number,
default: 0,
min: 0,
max: 5
}
})

const locationSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
rating: ratingSchema,

facilities: [String],
});

locationSchema.index({coords: '2dsphere'});

mongoose.model('Location', locationSchema);

当我打电话

const Loc = mongoose.model('Location');

const locationsReadOne = (req, res) => {
Loc
.findById(req.params.locationid)
.exec((err, location) => {
if (!location) {
return res.status(404).json({"message":"location not found"});
} else if (err) {
return res.status(404).json(err);
}
console.log("locationsReadOne:",location);
res.status(200).json(location);
});
};

它返回架构,但未返回评级字段。这是返回对象的控制台日志:

locationsReadOne: {
facilities: [ 'Hot drinks', 'Food', 'Premium wifi' ],
_id: 5f88bfdc4df4ca7709462865,
name: 'Starcups',
address: '125 High Street, Reading, RG6 1PS'
}

如果我调用 Loc.aggregate,则返回评级字段:

{
_id: 5f8b2ee15b0b6784a847b600,
facilities: [ 'Tea', ' Restroom' ],
name: 'Tea Leaf',
address: '2192 Green St.',
rating: 0,

}
{
_id: 5f88bfdc4df4ca7709462865,
name: 'Starcups',
address: '125 High Street, Reading, RG6 1PS',
rating: 3,
facilities: [ 'Hot drinks', 'Food', 'Premium wifi' ]
}

知道为什么会这样吗?我可以清楚地看到 MongoDB 指南针中每个文档中的评级字段,它们都列为 Double 类型。为什么它们被汇总返回,而不是在 findById(id) 甚至 find() 中返回?

谢谢。

最佳答案

当您在 mongoose 中使用 find 时,它将使用模式中的字段填充文档。例如 - 如果您从模式中删除一个字段,您可能不会在找到的文档中看到它,即使它在数据库中也是如此。 Aggregate 和 Compass 向您准确显示数据库中的内容,因此数据就在那里,只是没有填充到文档中,因为它在模式中看不到它。

原因是您的 ratingSchema 是一个具有 rating 属性的对象。所以 Mongoose 正在寻找类似的东西:

{
name: ...
rating: {
rating: 2
}
}

并没有找到它,所以它没有填充。要解决此问题,我不会将评级定义为子模式,而是将您的模式定义为

const locationSchema = new mongoose.Schema({ 
name: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
rating: {
type: Number,
default: 0,
min: 0,
max: 5
},
facilities: [String],
});

关于node.js - Mongoose findById 没有返回所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64490206/

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