编辑:我发现在using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<Package> packages = doc.Descendants("Package").Select(x => new Package() {
Shiptracknum = (ulong)x.Element("TrackNumber"),
PackageWeight = (string)x.Element("PackageWeight"),
items = x.Elements("Items").Select(y => new Item() {
ShipDescription = (string)y.Element("Description"),
EndUserPOnumber = (string)y.Element("EndUserPOLineNo")
}).ToList()
}).ToList();
}
}
public class Package
{
public ulong Shiptracknum { get; set; }
public string PackageWeight { get; set; }
public List<Item> items { get; set; }
}
public class Item
{
public string ShipDescription { get; set; }
public string EndUserPOnumber { get; set; }
}
}
方法内运行的console.log(this)
只返回哈希和盐。我不确定为什么会发生这种情况,但是它表明setPassword
没有引用模型。
我有以下架构,其中包含以下实例方法:
this
此处调用实例方法,然后保存用户:
let userSchema = new mongoose.Schema({
username: {type: String, required: true},
email: {type: String, required: true, index: {unique: true}},
joinDate: {type: Date, default: Date.now},
clips: [clipSchema],
hash: {type: String},
salt: {type: String}
})
userSchema.methods.setPassword = (password) => {
this.salt = crypto.randomBytes(32).toString('hex')
this.hash = crypto.pbkdf2Sync(password, this.salt, 100000, 512, 'sha512').toString('hex')
}
但是,当我在mongo CLI中查看let user = new User()
user.username = req.body.username
user.email = req.body.email
user.setPassword(req.body.password)
user.save((err) => {
if (err) {
sendJsonResponse(res, 404, err)
} else {
let token = user.generateJwt()
sendJsonResponse(res, 200, { 'token': token })
}
})
集合时,没有提到users
或hash
。
salt
答案 0 :(得分:12)
它不工作的原因是因为我使用的是箭头方法。我必须使它成为正常的功能:
userSchema.methods.setPassword = function (password) {
原因是因为箭头函数对this
的处理与常规函数不同。有关更多详细信息,请参阅以下内容: