【发布时间】:2017-07-18 00:42:10
【问题描述】:
这似乎是一个模糊的问题,但我会尽力解释。作为旁注,我对使用猫鼬很陌生:)
我有一个猫鼬模式为每个用户存储不同的值,就像这样......
let userSchema = mongoose.Schema({
user: { type: String, required: true, unique: true },
pass: { type: String, required: true },
files: [{ type: String, required: false }],
});
“文件”键包含一个值数组,例如:
userSchema.files = [value1, value2, value3]
而且我希望每个值都连接到某种ID,这样当我调用指定的ID时,我就得到了指定的值。仅出于演示目的,它可能看起来像这样:
userSchema.files = [{value:value1, id: id1},
{value:value2, id: id2},
{value:value3, id: id3}]
然后我想找到指定的id,并在请求中返回它的“value”-key:
router.route("/home/:id")
.get(restrict, function(req, res) {
User.findOne({ user: req.session.Auth.username }, function(error, data) {
data.files.forEach(function(file) {
if (file.id === req.params.id) {
response.render("../home", file.value)
}
}
});
});
我该怎么做?尝试将对象推送到文件,但这并没有按预期工作。阅读有关 ObjectId 的内容,但不太了解。 有什么建议吗?
【问题讨论】:
-
你得到的
data正确吗?您是否面临插入或检索的问题? -
@RaR 我在插入时遇到问题!
-
你试过什么?插入代码在哪里?
-
@RaR。我使用 .findOne 找到了指定的用户,并且在回调函数中我刚刚输入了 user.files = {value: req.body.value, id: 123}。然后数据库将每个值分别保存在一个数组中,例如:["req.body.value", "123"]
标签: javascript node.js mongodb express mongoose