为什么猫鼬 save() 不使用嵌套模式的默认值更新现有文档?



我有以下模式猫鼬:

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const getRating = ({ maxScore }) => ({
type: new Schema(
{
score: {
type: Number,
default: 0
},
maxScore: {
type: Number,
default: function() {
console.log('inside default')
return maxScore
}
}
},
{ _id: false }
)
})
const BrandRating = new Schema(
{
varietyOfProducts: {
overall: getRating({ maxScore: 18 }),
userFeedback: getRating({ maxScore: 9 }),
other: getRating({ maxScore: 9 })
}
{ _id: false }
const Brand = new Schema({
rating: {
type: BrandRating,
required: true
},
slug: String
)

我在mongodb中已经有很多Brand文档,现在我需要rating对象,它是一个嵌套的模式,每个字段也是一个具有默认值的嵌套模式。因此,现在我想运行数据库中的所有Brand文档,并保存它们,以便应用默认值。然而,它们没有被应用,我不确定问题是什么:

const [brand] = await Brand.find({ 'slug': 'test' })
await brand.save()
console.log('brand', brand) // doesn't have any of the new rating default values, logs { slug: 'test' }  
// { slug: 'test' }  

此外,我没有看到console.log语句甚至在defaultmongoose函数中被调用。

@thammada.ts的帮助下,我终于学会了如何设置默认值。关键是将一个空对象设置为BrandRating模式上的默认对象,并在getRating:内的最低级别上定义实际默认对象

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const getRating = ({ maxScore }) => ({
type: new Schema(
{
score: {
type: Number
},
maxScore: {
type: Number
}
},
{ _id: false }
),
default: {
score: 0,
maxScore
}
})
const BrandRating = new Schema(
{
varietyOfProducts: {
overall: getRating({ maxScore: 18 }),
userFeedback: getRating({ maxScore: 9 }),
other: getRating({ maxScore: 9 })
}
{ _id: false }
const Brand = new Schema({
rating: {
type: BrandRating,
required: true,
default: {}
},
slug: String
)

最新更新