Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5011

How do I access `findAndModify` method from Mongo in Node (with Mongoose)?

This is /models/joke.js:

var mongoose    = require ('mongoose')
    , database  = mongoose.connect('localhost', 'joke', { server: { poolSize: 3 } });

var jokeSchema = mongoose.Schema({
  content: String,
  upvotes: {
    type: Number,
    default: 0
  },
  downvotes: {
    type: Number,
    default: 0
  },
  views: {
    type: Number,
    default: 0
  },
  published: {
    type: Boolean,
    default: true
  },
  author_id: Number,
  created: {
    type: Date,
    default: Date.now
  }
});

var Joke = mongoose.model('Joke', jokeSchema);

module.exports = Joke;

And I'm doing this to check if something exist — if doesn't, then create:

var Joke = require ('./models/joke');

// ...

Joke.findAndModify({
  query: {
    content: content
  },
  update: {
    $setOnInsert: {
      content: "test",
    }
  },
  new: true,
  upsert: true
});

But my console shout me the following:

TypeError: Object function model(doc, fields, skipId) {
    if (!(this instanceof model))
      return new model(doc, fields, skipId);
    Model.call(this, doc, fields, skipId);
  } has no method 'findAndModify'

I can understand the reason for the error – I'm calling it through a model instead of a collection, but how do I access my Jokes' collection methods?

I mean, all of the examples were using db.collection.findAndModify, but what is this db.collection? How do I call it?

Upvotes: 4

Views: 5177

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312149

To access findAndModify update functionality from Mongoose, use findOneAndUpdate:

Joke.findOneAndUpdate(
  { content: content },
  { $setOnInsert: { content: "test" } },
  { new: true, upsert: true },
  callback
);

Upvotes: 6

Related Questions