英文:
Trying to split Mongoose models out into sud documents
问题
我确信这一定是某处语法问题。我有一个Mongoose模型,其中的一部分看起来是这样的:
SMS_Data: {
_id: false,
SMS_User: [{
Username: {
type: String
},
Password: {
type: String
}
}]
}
这是正常的,但我试图将其拆分为子文档。所以我创建了一个名为SMS_User.js的模型,内容如下:
const mongoose = require('mongoose');
const sms_user = mongoose.Schema({
SMS_User: {
Username: {
type: String
},
Password: {
type: String
}
}
})
module.exports = sms_user;
我通过以下方式将其引入主模型:
const sms_user = require('./SMS_User');
并尝试更改主模型,使其如下所示:
SMS_Data: {
_id: false,
SMS_User: [sms_user]
}
但这不起作用。与我预期的基于Username和Password选择用户不同。但当我从我的登录控制器中使用以下方式时:
const user = await my_model.findOne({ 'SMS_Data.SMS_User.Username': userId, 'SMS_Data.SMS_User.Password': userPw });
它只选择集合中的第一条记录,而不是我使用非嵌套版本的模型时所期望的正确记录。这让我认为子模型的嵌套可能有问题。
就像我说的,这可能非常明显,但我只是看不出我哪里错了。
提前谢谢。
英文:
I'm sure this is a syntax issue somewhere along the way. I've got a Mongoose model where part of it looks like this:
SMS_Data: {
_id: false,
SMS_User: [{
Username: {
type: String
},
Password: {
type: String
}
}]
}
This works fine, but I'm trying to split things out into subdocuments. So I've created a SMS_User.js model that looks like this:
const mongoose = require('mongoose');
const sms_user = mongoose.Schema({
SMS_User: {
Username: {
type: String
},
Password: {
type: String
}
}
})
module.exports = sms_user;
I require it into the main model using:
const sms_user = require('./SMS_User');
And tried changing the main model to now read like this:
SMS_Data: {
_id: false,
SMS_User: [sms_user]
}
But this doesn't work. Instead of selecting the user I expected, based on the Username and Password. But when I use this from my login controller:
const user = await my_model.findOne({ 'SMS_Data.SMS_User.Username': userId, 'SMS_Data.SMS_User.Password': userPw });
it just selects the first record in the collection, instead of the correct one when I use the un-nested version of the model. Which suggest to me that the nesting of the sub model is wrong.
Like I say this could be glaringly obvious, but I'm just not seeing where I'm going wrong.
Thanks in advance.
答案1
得分: 1
你已经错误地拆分了模式,因为你添加了额外的嵌套层级(即'SMS_Data.SMS_User.SMS_User.Username'
等)。
你需要从sms_user
模式中移除SMS_User
。
英文:
the way you have broken down the schema is wrong since you have added an extra level of nesting (i.e 'SMS_Data.SMS_User.SMS_User.Username'
etc).
You need to remove the SMS_User
from sms_user
schema
const sms_user = mongoose.Schema({
Username: {
type: String
},
Password: {
type: String
}
})
const parentSchema = mongoose.Schema({
//other fields
SMS_Data: {
_id: false,
SMS_User: [sms_user]
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论