この記事は 約 0分38秒 で読めます。
node-mongooseっていうmongoDBのデータ処理を簡単にしてくれるモジュールがnode.jsにはあります。
今回は、そのnode-mongooseを使って目的の配列にデータを追加・削除する方法です。
こんなモデルを定義したとします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
'use strict'; var mongoose = require('bluebird').promisifyAll(require('mongoose')); var Schema = mongoose.Schema; var ScrapingSchema = new Schema({ contents: [ { title :String, content :String, createdAt: { type: Date, default: Date.now } } ], createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Scraping', ScrapingSchema); |
★追加する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Scraping.update( {_id: 'ID'}, {$push: { contents: { title: 'TITLE', content: 'CONTENT' } }}, function(err, num){ if (err) { console.log(err); } if(num === 0) { } console.log('追加'); } ); |
★削除する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Scraping.update( {_id: 'ID'}, {$pull: { contents: {_id: 'CONTENTID'} }}, function(err, num){ if (err) { console.log(err); } if(num === 0) { } console.log('削除'); } ); |
色々やってみた結果、これでうまく動いてくれています。
(毎度思うんだけど、正しいの?これw)
以上です。