要学习MEAN堆栈(使用Mongoose),我正在创建一个StackOverflow类型的应用程序 . 我有问题存储在Mongo(v3.0.7)中,并且它们有Answer子文档 .
我试图增加一个答案的投票,但当问题返回时它是空的 . 我很确定查询有问题,特别是在我试图通过我需要修改的ID获得答案的地方 .
问题架构:
var questionsSchema = new mongoose.Schema({
answers: [ answerSchema ],
});
答案架构:
var answerSchema = new mongoose.Schema({
votes: { type: Number, default: 0 },
});
查询_id返回null:
Question.findOneAndUpdate(
{_id: req.params.questionId, 'answers._id': req.params.answerId },
{ $inc: { 'answers.$.votes': 1 } },
{ new: true },
function(err, question){
if (err) { return next(err); }
//question is returned as NULL
res.json(question);
});
查询0票有效:
Question.findOneAndUpdate(
{_id: req.params.questionId, 'answers.votes': 0 },
{ $inc: { 'answers.$.votes': 1 } },
{ new: true },
function(err, question){
if (err) { return next(err); }
//question is returned as NULL
res.json(question);
});
更新:通过Mongo查询结果返回:
db.questions.find({_id: ObjectId('562e635b9f4d61ec1e0ed953'), 'answers._id': ObjectId('562e63719f4d61ec1e0ed954') })
但是,通过Mongoose,返回NULL:
Question.find(
{_id: Schema.ObjectId('562e635b9f4d61ec1e0ed953'), 'answers._id': Schema.ObjectId('562e63719f4d61ec1e0ed954') },
2 回答
尝试使用mongoose Types ObjectID
http://mongoosejs.com/docs/api.html#types-objectid-js:
原始更新问题的最终答案:
您根本不需要
ObjectId
:Mongoose为您处理字符串 .
此外,使用
find()
并按_id
查询将生成长度为0或1的数组 . 使用findOne()
将返回文档对象 .