首页 文章

Mongoose在findOneAndUpdate()上返回NULL

提问于
浏览
2

要学习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 回答

  • 0

    尝试使用mongoose Types ObjectID

    http://mongoosejs.com/docs/api.html#types-objectid-js

    var ObjectId = mongoose.Types.ObjectId;
    Question.find({
        _id: '562e635b9f4d61ec1e0ed953',
       'answers._id': new ObjectId('562e63719f4d61ec1e0ed954')
    })
    

    原始更新问题的最终答案:

    Question.findOneAndUpdate(
       {_id: req.params.questionId, 
        'answers._id': new ObjectId(req.params.answerId) },
       { $inc: { 'answers.$.votes': 1 } },
       { new: true },
       function(err, question){
         if (err) { return next(err); }
         res.json(question);
       });
    
  • 2

    您根本不需要 ObjectId

    Question.findOne({_id: "562e635b9f4d61ec1e0ed953"}, callback)
    

    Mongoose为您处理字符串 .

    此外,使用 find() 并按 _id 查询将生成长度为0或1的数组 . 使用 findOne() 将返回文档对象 .

相关问题