【发布时间】:2021-06-07 08:56:55
【问题描述】:
我正在尝试创建一个 JSON-api 来管理待办事项。当用户使用 post 请求创建文档时,服务器返回一个 token 和创建的文档的 id 本项目使用 mongodb 保存数据,使用 mongoose 发出请求。
这是一个测试应用程序,我想练习自己在文档的name、待办事项、token中使用加密。
现在我处于存在 options 的情况,我需要在设置对象中保存 protectedWithToken 值。 它似乎不起作用,所以我添加了几个 console.log() 函数。
这是 mongodb 集合的架构:
架构
const toDoSchema = mongoose.Schema({
"name": {
type: String
},
"todo": {
type: String,
required: true
},
"iv": {
type: String
},
"secretToken": {
type: String,
required: true,
unique: true
},
"options": {
type: Object,
required: true
}
}, { collection: config.collectionName });
保存我的文档的代码
console.log('fast comparison before validation; wants',mem.options.protectedWithToken , 'already is',query.options.protectedWithToken)
if (query.options.protectedWithToken === true || mem.options.protectedWithToken !== query.options.protectedWithToken) {
// user didn't give token, and the document is protected
if (!request.token) {
// ......
}
// compare token values.
if (request.token !== tokencontent) {
// ....
}
}
try {
// save protectedWithToken to database
console.log('before query.... = ...',query.options)
query.options.protectedWithToken = mem.options.protectedWithToken
console.log('after query.... = ...','database options',query.options, 'request options',mem.options)
// save document
updatequery = await query.save();
console.log('saved:', updatequery.options.protectedWithToken)
// declare response body
result.status = 200
result.id = query._id
result.error = "document saved"
// send response
res.status(result.status).json(result)
一切似乎都很好......除了一件小事。它不会将 options.protectedWithToken 更新到数据库。 'saved:', updatequery 返回选项
程序返回什么
我发送了一个"options": { "protectedWithToken": true } 请求。
使用正确的令牌,服务器没有返回错误。
fast comparison before validation; wants true already is false
before query.... = ... (db) { protectedWithToken: false }
after query.... = ... (db) { protectedWithToken: true } (request) { protectedWithToken: true }
saved: true
如你所见,已保存为真,那意味着真应该保存在数据库中。我查看了cloud.mongodb.com 中的选项。他们说 options.protectedWithToken 是假的。
更新/修复
通过将 "options": {type: Object} 更改为 "options": {type: String} 并在插入数据库之前将对象字符串化为 json 使其工作。
【问题讨论】:
-
您能否包含一些更相关的代码,例如
query来自哪里? (在“保存我的文档的代码”部分) -
在函数开始时,我从 mongodb 请求旧数据,查询是它的响应。简化,查询 = 旧数据
标签: node.js mongodb mongoose boolean