【问题标题】:Populate a field with Mongoose使用 Mongoose 填充字段
【发布时间】:2018-02-08 00:35:40
【问题描述】:

好吧,伙计们,

我正在开发一个电影应用程序来练习我的角度和节点技能。我正在使用猫鼬来处理我的数据库,目前我正在研究“填充”。 我有以下用户模式,我想知道如何在我的 ratings 键中填充对象。 ratings 是一个对象数组,这些对象看起来像这样{movie:{type: Schema.Types.ObjectId, ref: 'Movie'}, rating:Number}。我想知道如何填充该数组中每个对象的电影键。我认为节点路由文档中的结构应该如下所示,但我不知道在.populate()中输入什么。

User.find({'_id':someNumber).populate(noIdeaWhatToWriteHere).exec()

user.js 模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');


var schema = new Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    password: {type: String, required: true},
    email: {type: String, required: true, unique:true},
    ratings: [{movie:{type: Schema.Types.ObjectId, ref: 'Movie'}, rating:Number}],
    reviews: [{movie:{type: Schema.Types.ObjectId, ref: 'Movie'}, review:String}]
}, { usePushEach: true });

schema.plugin(mongooseUniqueValidator);

module.exports = mongoose.model('User', schema);

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您唯一需要记住的是,populate 中的名称必须是复数形式。

    User.find({'_id':someNumber).populate('movies').exec()
    

    【讨论】:

    • 我试过了,但它返回 {movie: 5a6b16485970c21cbc5bf2b3, rating: 4 },所以它没有被填充。
    • 你试过电影吗?也许是区分大小写的。您必须在填充方法中编写它,就像编写集合名称一样
    【解决方案2】:

    我找到了解决办法:

    我使用了 .populate('ratings.movi​​e'),现在它起作用了。

    【讨论】:

      猜你喜欢
      • 2012-01-22
      • 2017-05-21
      • 2013-07-06
      • 2021-09-06
      • 1970-01-01
      • 2015-09-19
      • 2019-01-01
      • 2015-06-09
      • 2020-11-21
      相关资源
      最近更新 更多