用猫鼬更新记录 [英] Updating a record with mongoose

查看:173
本文介绍了用猫鼬更新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习MEAN堆栈应用程序,并且正在使用电视监视列表应用程序。我建立了api成功,没有季节领域的模型。现在我想添加这个字段,以便用户可以在文档中添加季节和剧集来跟踪他们观看的剧集。通过尝试和错误,我发现我在mongo shell中使用的查询来更新剧集对象中的一个字段,但是我无法创建正确的语法来在我的路由中使用mongoose。有人可以在router.put看到我的tele.js路由,并告诉我有什么问题。



模型(TVSeries.js)


$


var tvSchema = new Schema({
标题:String,
poster:String,
评分:String,
program_time:Number,
network:String,
airs_on:[],
streams_on:[],
类型:[],
季节:[
season_number:数字,
剧集:[
{
episode_number:Number ,
title:String,
watched:Boolean
}
]
]
},{collection:'tvShows'});

module.exports = mongoose.model('tv',tvSchema);

路线(tele.js)

  var express = require('express'); 
var router = express.Router();
var TV = require('../ models / TVSeries.js');

/ * GET主页。 * /
router.get('/',function(req,res,next){
res.render('index',{title:'Your Watchlist'});
} );

router.get('/ api / shows /:id / seasons',function(req,res){
TV.findById(req.params.id,'seasons',function (err,data){
if(err){console.log(err)}
else {res.json(data)};
});
});

router.put('/ api / shows /:id / seasons /:sid',function(req,res){
var setField = {
seasons:[
{
season_number:req.params.sid,
episodes:[
req.body
]
}
]
}

TV.findOneAndUpdate({_ id:req.params.id},setField,{upsert:true},function(err,results){
if(err){console。 log(err)}
else {
console.log(setField);
res.json(results)
}
})
})

module.exports = router;

Mongo Shell命令

  db.tvShows.update({ _编码:的ObjectId( '######################')},{$组: {'seasons.1.episodes.1.title':'这是我的标题更改'}})


解决方案

您可以使用& elementMatch 来查找阵列中的欲望季节,而在setField对象中,您可以使用位置 $ 运算符,用于标识查询中匹配的元素。



问题是如果没有找到任何季节匹配 season_number ,文档将不会更新。在这种情况下,您可以设置另一个更新查询,以便在季节数组中添加此季节。

 code> router.put('/ api / shows /:id / seasons /:sid',function(req,res){

var query = {
_id :req.params.id,
seasons:{
$ elemMatch:{
season_number:req.params.sid
}
}
}

var setField = {
$ addToSet:{
seasons。$。episodes:req.body
}
}

TV.findOneAndUpdate(query,setField,{upsert:true},function(err,results){
if(err&& err.code == 16836){//没有文档匹配
var season = {
season_number:req.params.sid
episodes:[req.body]
}
TV.findOneAndUpdate({ _id:req.params.id},{$ push:{seasons:season}},function(err,result){
console.log(Inserted document in array);
res.json(result)
});
}
else if(err){
console.log(err);
res.status(500).send('Something wrong!');
}
else {
console.log(setField);
res.json(results)
}
})
})

您可以在这里查看 here 某些mongodb数组运算符



希望有帮助。


I'm learning MEAN stack applications and am working on a tv watchlist app. I built the api successfully without the seasons field in the model. Now I'd like to add this field so that a user can add seasons and episodes to the document to keep track of episodes they have watched. Through trial and error I found the query I'd use in the mongo shell to update a field in the episodes object but I can't create the right syntax to do this with mongoose inside my route. Can someone look in my tele.js routes at the router.put and tell me what's wrong.

Models (TVSeries.js)

var mongoose = require('mongoose')
var Schema = mongoose.Schema

var tvSchema = new Schema({
  title:String,
  poster:String,
  rated:String,
  program_time:Number,
  network:String,
  airs_on:[],
  streams_on:[],
  genre:[],
  seasons:[
            season_number:Number,
            episodes:[
                       {
                         episode_number:Number,
                         title:String,
                         watched:Boolean
                       }
                     ]
          ]
}, {collection: 'tvShows'});

module.exports = mongoose.model('tv', tvSchema);

Routes (tele.js)

var express = require('express');
var router = express.Router();
var TV = require('../models/TVSeries.js');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Your Watchlist' });
});

router.get('/api/shows/:id/seasons', function(req, res){
    TV.findById(req.params.id, 'seasons', function(err, data){
        if(err){console.log(err)}
        else{res.json(data)};
    });
});

router.put('/api/shows/:id/seasons/:sid', function(req, res){
    var setField = {
        seasons:[
            {
                season_number:req.params.sid,
                episodes:[
                    req.body
                    ]
            }
        ]
    }

    TV.findOneAndUpdate({"_id":req.params.id}, setField, {upsert:true}, function(err, results){
       if(err){console.log(err)}
       else{
           console.log(setField);
           res.json(results)
       }
    })
})

module.exports = router;

Mongo Shell command

db.tvShows.update({"_id":ObjectId('######################')},{$set: {'seasons.1.episodes.1.title':'This is my title change'}})

解决方案

You can use &elementMatch to find the desire season in the array, and in the setField object you can use the positional $ operator which identify the element matched in the query.

The problem is that if it doesn't find any season that match the season_number, the document will not be updated. In this case you can set another update query to add this season in the seasons array.

router.put('/api/shows/:id/seasons/:sid', function(req, res){

  var query = {
    "_id": req.params.id,
    "seasons": { 
      $elemMatch: { 
        "season_number": req.params.sid 
      } 
    }
  }

  var setField = {
    $addToSet: {
      "seasons.$.episodes": req.body
    }
  }

  TV.findOneAndUpdate(query, setField, {upsert:true}, function(err, results){
    if (err && err.code == 16836) { // no document was matched
      var season = {
        "season_number": req.params.sid
        "episodes": [ req.body]
      }
      TV.findOneAndUpdate({"_id": req.params.id}, {$push: {"seasons": season}} , function(err, result) {
          console.log("Inserted document in array");
          res.json(result)
      }); 
    }
    else if (err){
       console.log(err);
       res.status(500).send('Something wrong!');
    }
    else {
       console.log(setField);
       res.json(results)
    }
  })
})

You can see here some mongodb array operators.

Hope it helps.

这篇关于用猫鼬更新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆