gpt4 book ai didi

node.js - Mongoose 虚拟机是否困惑?

转载 作者:太空宇宙 更新时间:2023-11-03 23:43:23 24 4
gpt4 key购买 nike

好的,我有这个 SchemaOptions、Schema、Constructor 和 virtual。

var schemaOptions = {
toObject: { virtuals: true }, toJSON: { virtuals: true }
};

var clientSchema = mongoose.Schema ({
company: { type: String, trim: true, required: true, unique: true },
monthly_cost: { type: Number, trim: true, required: true },
sms_cost: { type: Number, trim: true, required: true },
...
}, schemaOptions);

var Client = mongoose.model('Client', clientSchema);

clientSchema.virtual('creationDate').get(function () {
return dateFormat(this._id.getTimestamp(), 'isoDate');
});

再往下我有这条路线:(注意for循环中的注释代码,稍后我们将删除此注释)

app.get('/superadmin', function(req, res) {
Client.find({}, 'company monthly_cost sms_cost', function (err, docs) {
if (err) return handleError(err);

for (var i = 0, tot=docs.length; i < tot; i++) {
// docs[i].creationDate = 'strange variable ' + i;
}

console.log(docs);

res.render('superadmin/index', {
title: 'Superadmin',
docs: docs,
path: req.route.path,
});
});
});

在我的 Jade View 中,我有以下代码:

p #{docs};
each client in docs
tr
td #{client.company}
td #{client.creationDate}
...

但是问题来了:

在我的 route ,我有: console.log(docs); 输出类似于“YYYY-MM-DD”的字符串,这是预期的并且很好。

在我看来,我早期有: console.log(docs); 它也输出正确的字符串:'YYYY-MM-DD',这是预期的并且很好。

但在我看来:#{client.creationDate} 不会输出任何内容!我不明白为什么。

如果我们现在像这样激活 for 循环中的注释行:

for (var i = 0, tot=docs.length; i < tot; i++) {
docs[i].creationDate = 'strange variable ' + i;
}

... #{cl​​ient.creationDate} 将输出'奇怪的变量[0-2]'。但我之前的两个 console.log(docs) 仍然会输出预期的creationDate 字符串。

我不明白这一点..似乎creationDate同时是两个变量。

Mongoose Virtuals 让我发疯,我真的不明白为什么我要向他们提示,因为它似乎可以动态地将键值添加到获取的 Mongoose 对象中。好吧,它们不会出现在 console.log 中...但它们以某种方式存在,我可以像这样使用它们:在我看来,#{cl​​ient.creationDate}

最佳答案

此代码不正确:

var Client = mongoose.model('Client', clientSchema);

clientSchema.virtual('creationDate').get(function () {
return dateFormat(this._id.getTimestamp(), 'isoDate');
});

在将架构“编译”为模型之前,您必须完全配置架构。它不是动态的。模型编译完成后,对架构的进一步更改不会生效。

关于node.js - Mongoose 虚拟机是否困惑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18850749/

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