Quinton Pike
Quinton Pike

Reputation: 3861

Mongoose/MongoDB - Saving a record to overwrite current data:

So I have a object in the DB that is basically blog posts, there is a array of ObjectID's in there that reference the Categories collection.

So

Posts = {
   title: String,
   Content: String,
   Categories: [{
       type: ObjectID,
       ref: 'Categories'
   }]

I can create the posts fine, problem comes when I try to update them:

post.title = 'hi';
post.content = 'content';
post.categories = ['44523452525','4e1342413421342'];

post.save(function(){});

For some reason it will ADD those 2 categories instead of wiping the categories array and inserting those.

How do I get it to remove those and insert new ones?

Upvotes: 2

Views: 6686

Answers (1)

mpobrien
mpobrien

Reputation: 4962

I tried to reproduce this behavior but I couldn't - here's the code sample I ran:

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

mongoose.connect('mongodb://localhost/testjs');

PostSchema = new Schema({
  title:String,
  content:String,
  cats:[]
});
var Post = mongoose.model('Post', PostSchema);

var mypost = new Post()
mypost.title = "x"
mypost.content = "y"
mypost.cats = ['a','b','c']
mypost.save(
  function(err){
    mypost.cats = ['d','e']
    mypost.save()
  }
);

After the second call to save() the array contains only what it was set to ("d","e"). Can you try it and see if you get the same result? Maybe it's related to mongoose version, or something.

Upvotes: 5

Related Questions