以下是我的架构的相关部分,我将在其中预留空间":
var spaceSchema = new mongoose.Schema({
spaceName: String,
scheduledDates: [{
scheduledDates: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
username: String
}
}]
});
作者应该是当前登录的用户。以下是我更新这些字段的路线:
router.put('/:space_id/schedule', function(req, res) {
Space.findByIdAndUpdate(req.params.space_id, {
'$push': { 'scheduledDates': req.body.space, 'author': req.user._id }
}, { "new": true, "upsert": true }, function(err, space) {
if (err) {
console.log(err);
} else {
console.log(req.body.space);
}
});
});
我无法访问"作者"正确的,因为它在数组内部。如何更新此阵列,添加新日期和用户进行预订?
谢谢
更新
我尝试使用" _id"而不是" id"在我的财产,但得到相同的结果。似乎忽略了作者"字段,只保存" scheduledDates"
所以架构是这样的:
scheduledDates: [{
scheduledDates: String,
author: {
_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
username: String
}
}]
然后在我的路线中,我改变了我的想法并推动了39>:
'$push': { 'scheduledDates': req.body.space, 'author._id': req.user._id }
更新2
改变了我推送对象的方式:
'$push': {
'scheduledDates': {
'scheduledDates': req.body.space,
'author': { _id: req.user._id, username: req.user.username }
}
}
现在我收到以下错误:
message: 'Cast to string failed for value "{ scheduledDates: \'04/11/2017\' }" at path "scheduledDates"',
name: 'CastError',
stringValue: '"{ scheduledDates: \'04/11/2017\' }"',
kind: 'string',
value: [Object],
path: 'scheduledDates',
reason: undefined } } }