2015-11-11 2 views
0

Написав мое приложение для домашних животных, я встретил некоторую проблему. Я использую библиотеки nodejs и mongojs для работы с mongo. Я написал код:

db.users.findOne({_id: ObjectId(id)}, function (err, doc) { 
 
    if (err) { 
 
     res.status(500).send('Can not find name for user.'); 
 
     return; 
 
    } 
 

 
    userName = doc.userName; 
 

 
    db.notes.findOne({userId: id}, function (err, doc) { 
 
     if (!doc) { 
 
     db.notes.insert({ 
 
      userId: id, 
 
      userName: userName, 
 
      notes: [req.body] 
 
     }, function (err, doc) { 
 
      if (err) { 
 
      res.status(500).send('Server error.'); 
 
      return; 
 
      } 
 

 
      res.json(doc); 
 
     }); 
 
     } else { 
 
     db.notes.update({ 
 
      userId: id 
 
     }, { 
 
      $push: { 
 
      'notes': req.body 
 
      } 
 
     }, 
 
     function (err, doc) { 
 
      if (err) { 
 
      res.status(500).send('Server error.'); 
 
      return; 
 
      } 
 

 
      res.json(doc); 
 
     }); 
 
     } 
 

 
     if (err) { 
 
     res.status(500).send('Server error.'); 
 
     return; 
 
     } 
 
    }); 
 
    });

Теперь он выглядит как обратный вызов ад для меня. Я пытаюсь изменить мой код, чтобы сделать его более удобным для чтения и использования метода сохранения:

users.findOne({_id: makeObjectId(id)}, function (err, doc) { 
 
    if (err) { 
 
     res.status(500).send('Can not find name for user.'); 
 
     return; 
 
    } 
 

 
    userName = doc.userName; 
 

 
    notes.save({ 
 
     userId: id, 
 
     userName: userName 
 
    }, { 
 
     $push: { 
 
     'notes': req.body 
 
     } 
 
    }, function (err, doc) { 
 
     if (err) { 
 
     return res.status(500).send('Error during inserting the note'); 
 
     } 
 

 
     res.status(200).send(doc); 
 
    }); 
 
    });

Теперь он выглядит более удобным для чтения, но не работает. Возможно ли в MongoDB комбинировать метод сохранения (чтобы можно было изменить документ, если он существует, и создать новый, если нет) и $ push для одного из параметров? Спасибо заранее.

+0

Вы действительно хотите [ '.update()'] (http://mongodb.github.io/node-mongodb-native/2.0/api /Collection.html#update) или даже ['.findOneAndUpdate()'] (http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndUpdate), а затем, конечно, [ «upsert»] (https://docs.mongodb.org/manual/reference/method/db.collection.update/#upsert-option), как показано в основной документации. –

+0

Благодарим вас за ответ. Не могли бы вы быть добрыми, чтобы предоставить код нажатием. Я не уверен, что понимаю, как реализовать его с помощью .update(). –

+0

Непонятно, что вы «добавляете в массив». В частности, в сочетании с «upsert» существует важное различие между тем, является ли это ['$ addToSet'] (https://docs.mongodb.org/v3.0/reference/operator/update/addToSet/) или более сложная операция с несколькими обновлениями. –

ответ

0

Bingo !!!

notes.update({ 
 
     userId: id, 
 
    }, { 
 
     $set: { 
 
     userId: id, 
 
     userName: userName 
 
     }, 
 
     $push: { 
 
     notes: req.body 
 
     } 
 
    }, { 
 
     upsert: true 
 
    }, function (err, doc) { 
 
     if (err) { 
 
     return res.status(500).send('Error during inserting the note'); 
 
     } 
 
     res.status(200).send(doc); 
 
    });

Благодаря Blakes Seven

Смежные вопросы