gpt4 book ai didi

node.js - Mongoose 填充为实例对象

转载 作者:可可西里 更新时间:2023-11-01 09:15:14 26 4
gpt4 key购买 nike

当使用 mongoose 的 populate 时,您可以取回文档,但它不是定义模式方法的对象实例。

var tweetSchema = new mongoose.Schema({
owner: { type: Schema.Types.ObjectId, ref: 'User' },
message: { type: String },
});

var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
});

userSchema.methods.test = function(){
return 'test'
}

Tweet.findOne({}).populate('user').exec(function(err,tweet){
console.log(tweet.user.test);
});

这将导致错误“无法读取未定义的属性‘userTwit’”,因为 tweet.user 只是一个散列而不是文档实例。有没有办法让 population 返回文档实例???

让这样的事情成为可能的好方法是什么?

最佳答案

除非您使用 lean(),否则填充的字段文档实例。

看起来你在 tweetSchema 中的 User 字段被称为 owner,而不是 user,所以这应该有效:

Tweet.findOne({}).populate('owner').exec(function(err, tweet){
console.log(tweet.owner.test());
});

关于node.js - Mongoose 填充为实例对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28206734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com