如何从Node(使用Mongoose)中的Mongo访问`findAndModify`方法?

时间:2014-12-24 16:50:28

标签: node.js mongodb

这是/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;

我这样做是为了检查是否存在某些东西 - 如果不存在,则创建:

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

// ...

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

但是我的控制台喊出了以下内容:

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'm calling it through a model instead of a collection,但如何访问我的笑话收集方法?

我的意思是,所有示例都使用db.collection.findAndModify,但这是db.collection是什么?我怎么称呼它?

1 个答案:

答案 0 :(得分:6)

要从Mongoose访问findAndModify更新功能,请使用findOneAndUpdate

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