我有以下架构:
var StorySchema = new Schema({
title: { type: String, required: true },
users: {
id: { type: Schema.ObjectId, ref: 'Users' },
creator: { type: Boolean }
},
maxlines: { type: Number, default: '10'},
lines: {
text: { type: String },
entered_at: { type: Date },
user: {
id: { type: Schema.ObjectId, ref: 'Users' }
}
},
created_date: { type: Date, default: Date.now },
updated_date: { type: Date, default: Date.now },
})
我想将数据推送到lines
,并尝试使用以下更新:
exports.update = function (req, res) {
Stories
.findOne({ _id: req.params.id }, function (err, story) {
if (err) {
res.json(200, {
success: "false",
message: err.message
})
} else {
story.maxlines = story.maxlines - 1
story.lines.push ({
text : req.body.text,
'user.id' : req.headers.id,
entered_at : new Date().toISOString()
})
story.save(function(err, story) {
if (err) {
res.json(200, {
success: "false",
message: err.message
})
} else if (story) {
res.json({
sucess: "true",
message: story
})
}
})
}
})
}
我收到TypeError: Object { user: {} } has no method 'push'
错误,不完全确定如何更新行和与该行关联的用户
答案 0 :(得分:1)
因为story.lines
不是数组。您可能需要更新Schema以将这些行转换为以这种方式键入Array:
var LineSchema = new Schema({
text: {
type: String
},
entered_at: {
type: Date
},
user: {
id: {
type: Schema.ObjectId,
ref: 'Users'
}
}
});
var StorySchema = new Schema({
title: {
type: String,
required: true
},
users: {
id: {
type: Schema.ObjectId,
ref: 'Users'
},
creator: {
type: Boolean
}
},
maxlines: {
type: Number,
default: '10'
},
lines: [LineSchema],
created_date: {
type: Date,
default: Date.now
},
updated_date: {
type: Date,
default: Date.now
},
})