看起来它不喜欢我设置嵌套架构的方式?
用户架构
const mongoose = require("mongoose");
const twitchSchema = mongoose.Schema(
{
id: Number,
login: String,
display_name: String,
type: String,
broadcaster_type: String,
description: String,
profile_image_url: String,
offline_image_url: String,
view_count: Number,
email: String,
created_at: String,
provider: String,
accessToken: String,
refreshToken: String,
},
{ _id: false }
);
const userSchema = new mongoose.Schema({
provider: {
youtube: {},
twitch: twitchSchema,
},
});
module.exports = mongoose.model("User", userSchema);
这就是我创建新文档的方式
const userModels = new UserModels();
userModels.provider[profile.provider].login = profile.login;
const result = await userModels.save()
最佳答案
您应该始终在问题中添加您遇到的错误。我已经尝试过您的代码并收到未定义的引用错误:
// Schema setup
const mongoose = require('mongoose');
const twitchSchema = mongoose.Schema(
{
id: Number,
login: String,
display_name: String,
type: String,
broadcaster_type: String,
description: String,
profile_image_url: String,
offline_image_url: String,
view_count: Number,
email: String,
created_at: String,
provider: String,
accessToken: String,
refreshToken: String,
},
{ _id: false }
);
const userSchema = new mongoose.Schema({
provider: {
youtube: {},
twitch: twitchSchema,
},
});
module.export = mongoose.model('User', userSchema);
// Driver code
const u = new User();
console.log(u);
const profile = {
provider: 'twitch',
login: 'dummy_login',
};
u.provider[profile.provider].login = profile.login;
console.log(u);
const res = await User.create(u);
console.info(res);
// Error
// { _id: new ObjectId("624e8901dc46c217a1461c41") }
// TypeError: Cannot set property 'login' of undefined
所以问题出在用户模型中设置登录字段时。您应该像这样调整您的 userSchema:
const userSchema = new mongoose.Schema({
provider: {
youtube: {},
twitch: { type: twitchSchema, default: {} },
},
});
请参阅 Mongoose documentation here 。 现在,如果您运行以下驱动程序代码,它就可以在 mongo 中创建记录。
const u = new User();
console.log(u);
const profile = {
provider: 'twitch',
login: 'dummy_login',
};
u.provider[profile.provider].login = profile.login;
console.log(u);
const res = await User.create(u);
console.info(res);
查看下面的日志:
{ _id: new ObjectId("624e8a9990d90dea47e7f62a") }
{
provider: { twitch: { login: 'dummy_login' } },
_id: new ObjectId("624e8a9990d90dea47e7f62a")
}
{
provider: { twitch: { login: 'dummy_login' } },
_id: new ObjectId("624e8a9990d90dea47e7f62a"),
__v: 0
}
关于node.js - 无法设置未定义的属性(设置 'login' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71580526/