填充后猫鼬调用子方法

时间:2018-08-13 21:12:31

标签: node.js mongodb mongoose

我想创建一种删除所有用户文件的方法。

//User Schema
var UserSchema = new Schema({
    username: String,
    files:[{ type: Schema.Types.ObjectId, ref: 'File' }]
});

//File Schema
var fileSchema = Schema({
    owner: { required: true, type: Schema.Types.ObjectId, ref: 'User' },
    filename: {type:String,required:true},
});
fileSchema.methods.deleteFromDisk = function () {
    //delete function
};

如何在所有用户文件上运行deleteFromDisk?我目前正在这样填充:

User.populate('files').exec(function (err, user) {
    console.log(user.files); //Shows files as json
    user.files.map(file=> {
        file.deleteFromDisk(); //ERROR - fileSchema.deleteFromDisk is not a function
    });
});

1 个答案:

答案 0 :(得分:0)

您在哪里定义用户文件模型?如果在定义模型后定义了架构实例方法,则可能是问题的原因。

示例:

const mongoose = require('mongoose');
const assert = require('assert');

const { Schema } = mongoose;

const wrongSchema = new Schema({
  name: String
});

const correctSchema = Schema({
  name: String
});

// define model before it's schema instance methods
const Wrong = mongoose.model('Wrong', wrongSchema);

wrongSchema.methods.customInstanceMethod = function () {
  console.log('My name is', this.name);
};

correctSchema.methods.customInstanceMethod = function () {
  console.log('My name is', this.name);
};

// define model after it's schema instance methods
const Correct = mongoose.model('Correct', correctSchema);

const iCorrect = new Correct({ name: 'correct' });
assert(iCorrect.customInstanceMethod); // it passes this assert
iCorrect.customInstanceMethod();  // => My name is correct

const iWrong = new Wrong({ name: 'wrong' });
assert(iWrong.customInstanceMethod); // => AssertionError [ERR_ASSERTION]: undefined == true
iWrong.customInstanceMethod();  // => TypeError: iWrong.customInstanceMethod is not a function