我正在尝试创建一个 JSON-api 来管理待办事项。当用户使用 post 请求创建文档时,服务器返回一个 token 和创建的文档的 id 本项目使用mongodb来保存数据,使用mongoose来发出请求。
这是一个测试应用程序,我想练习自己在文档的名称、待办事项、令牌中使用加密。
现在我有一个选项,我需要在设置对象中保存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
如你所见,saved为真,意味着真应该保存在数据库中。我查看了 cloud.mongodb.com
中的选项。他们说 options.protectedWithToken 是假的。
通过将 "options": {type: Object}
更改为 "options": {type: String}
并在插入到数据库之前将对象字符串化为 json 使其工作。
答案 0 :(得分:0)
我在您的架构中看到的一个问题是您尝试为 Object
设置的类型 options
。据我所知,文档没有将 Object
列为有效的 SchemaType。 (https://mongoosejs.com/docs/schematypes.html)
我想你要找的是Schema.Types.Mixed
,所以像这样
options : {
type: Schema.Types.Mixed,
required: true
}
或喜欢其中之一
options : Object
options : {}
options : mongoose.Mixed
注意(来自文档):
<块引用>由于 Mixed 是无模式类型,您可以将值更改为您喜欢的任何其他值,但 Mongoose 无法自动检测和保存这些更改。要告诉 Mongoose Mixed 类型的值发生了变化,您需要调用 doc.markModified(path),将路径传递给您刚刚更改的 Mixed 类型。
也许这已经解决了你的问题