Maria Jane
Maria Jane

Reputation: 2403

findOneAndUpdate mongoose in node.js failed

I got an error of Account.findOneAndUpdate is not a function using POSTMAN. Any clue what's wrong with my model below?

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');

var Account = new Schema({
    username: String,
    password: String,
    createAt: {type: Date, default: Date.now},
    status: {type: String, default: 'Active'}
});

Account.plugin(passportLocalMongoose);

module.exports = mongoose.model('accounts', Account);

module.exports.updateStatus = function(username,callback){
    var update = {status:'Completed'};
    Account.findOneAndUpdate({username:username},update).exec(callback);
}

I want to update the status to completed

When I do console.log(username) I'm able to see I can get the value.

Upvotes: 0

Views: 215

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

findOneAndUpdate is a method on the model, not the schema.

var AccountSchema = new Schema({
    username: String,
    password: String,
    createAt: {type: Date, default: Date.now},
    status: {type: String, default: 'Active'}
});

AccountSchema.plugin(passportLocalMongoose);

var Account = mongoose.model('accounts', AccountSchema);
module.exports = Account;

module.exports.updateStatus = function(username,callback){
    var update = {status:'Completed'};
    Account.findOneAndUpdate({username:username},update).exec(callback);
}

But you probably want to clean up your exports as you're using the model as your exports object but then adding updateStatus to that.

Upvotes: 2

Related Questions