How do I access the findAndModify method from Mongo to Node (using 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 do this to check if something exists - if not, then create:

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

// ...

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

But my console yells 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 cause of the error - I call it through the model instead of the collection , but how do I access my methods for collecting jokes?

I mean, all the examples used db.collection.findAndModify, but what is this db.collection? What should I call it?

+4
source share
1 answer

To access the update function findAndModifyfrom Mongoose, use findOneAndUpdate:

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

Source: https://habr.com/ru/post/1568908/


All Articles