【问题标题】:how do I query from parent model a array of other model in Mongoose?如何从父模型中查询 Mongoose 中的其他模型数组?
【发布时间】:2019-05-31 15:39:54
【问题描述】:

我有两个用于用户和待办事项的架构。每个待办事项都有一个所有者作为用户,每个用户都有一个待办事项数组。

// user.js
const TodoSchema = require('./todo').TodoSchema;

var UserSchema = mongoose.Schema({
	name: {
		type: String,
		required: true
	},
	todos: {
		type: [TodoSchema]
	}
});

module.exports.UserSchema = UserSchema;
module.exports.UserModel = mongoose.model('UserModel', UserSchema);


// todo.js
var TodoSchema = mongoose.Schema({
	body: {
		type: String, required: true
	},
	owner: {
		type: mongoose.Schema.Types.ObjectId,
		ref: 'UserModel',
		required: true
	}
});

module.exports.TodoSchema = TodoSchema;
module.exports.TodoModel = mongoose.model('TodoModel', TodoSchema);

我输入了这样的数据。

var nUser = new UserModel({
  name: "Alex
)};

nUser.save().then(user => {
  var t = new TodoModel({
    body: "my new todo",
    owner: user._id
  });
  t.save().then();
});

但问题是我想从特定用户那里获取所有待办事项,例如......正确的方法是什么?

UserModel.findOne({name: "Alex"})
.then(user => {
  // user.todos
});

附: 我可以像 TodoModel.find({owner: specific_user._id}) 一样执行此操作,但我希望来自 UserModel。

【问题讨论】:

    标签: javascript node.js database mongodb mongoose


    【解决方案1】:

    由于您要求正确的方法,我将从您的用户架构开始。如果要查找用户的所有待办事项,则不需要将待办事项文档放入用户文档中的数组中。所以你可能应该从你的架构中删除它。

    之后,您可以使用简单的聚合来获得所需的结果。

    UserModel.aggregate([
        {
          $match:{
            name:"Alex"
          }
        },
        {
          $lookup:{
            from:"todomodels",
            localField:"$_id",
            foreignField:"$owner",
            as:"todos"
          }
        }
      ])
    

    这将在同名数组中返回该用户的所有待办事项。

    【讨论】:

      猜你喜欢
      • 2015-04-18
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 2018-07-15
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多