Mongoose 预保存绑定/此关键字不起作用

问题描述 投票:0回答:2

架构定义

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var person = new Schema({
    name: {type : String}
})

person.pre('save', (next) => {
    console.log('in pre function and')
    console.log("this.name ",this.name);
    if (this.name == ' ') {
       // throw new console.error(' in valid name');
        console.log(err);
    }

    if (this.isNew == 'true') {
        console.log(this);
    } else {
        console.log(' false ' , this)
    }
    next();
})

const personModel = mongoose.model('personTable', person);
module.exports = {
    personModel
}

数据库

const mongoose = require ('mongoose');
const {personModel} = require('./schema');

mongoose.connect('mongodb://localhost/dataBase',{useNewUrlParser : true});
const db = mongoose.connection;

db.once('open',()=>{
    console.log(' Connection successful ');

    const prakash = new personModel({
        name : 'prakash'
    })

    
    prakash.save((err,data)=>{
        if(err)console.error(err);
        else console.log('data saved ',data);
    })
})

在架构定义文件中,当我注销时

this.name
并且它给出
undefined
我无法理解这种行为,我已经浏览了这个网站并关注了它,但仍然找不到识别错误的方法。

node.js mongodb mongoose this
2个回答
3
投票

mongo
mongoose
没有任何问题,它是箭头函数声明。

检查您已经发布的链接。示例中到处都有

function
关键字。

只需按照您通过此代码提供的示例进行操作即可:

Schema.pre('save', function (next) {...

您将得到以下内容

您可能想看看 StackOverflow 上的这些问题:

此外,MDN 有关箭头函数的 MDN 链接


0
投票

这里使用匿名函数而不是数组函数

Schema.pre('save', function (next) {...
© www.soinside.com 2019 - 2024. All rights reserved.