MongoDB和Mongoose一对多关系

64jmpszr  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(90)

我是新来的我有两个集合=>UserTask
每个用户可以有多个任务,但每个任务只能有一个用户。

用户架构:

const UserSchema = new Schema({
          name: {
            type: String, // type of the variable
            required: [true, "Please provide a name"], // this variable must be filled
          },
          tasks: [
            {
          type: mongoose.Schema.ObjectId,
          ref: "Task",
        },
      ],
    });

字符串

TaskSchema:

const TaskSchema = new Schema({
  title: {
    type: String, // type of the variable
    required: [true, "Please provide a title"], // this variable must be filled
  },
  user: {
    type: mongoose.Schema.ObjectId,
    required: true,
    ref: "User", // give reference to the user model
  },
});


下面的代码列出了所有任务数据及其用户

await Task.find().populate("user");


但是当我列出User数据时,task属性为空:

await User.find().populate(tasks");

创建任务体:

{
    "title": "Task 1",
    "user": "64afb6943c764b68ad9c1f61"
}


我的问题是,当我添加新任务时,我是否也应该将任务ID添加到MongoDB上的用户任务属性中?因为我无法通过这种方式读取用户的任务。

lvjbypge

lvjbypge1#

是的。你应该push()新的taskuser.tasks数组。

const user = await User.findById('64afb6943c764b68ad9c1f61');

const task = new Task({ title: 'Task 1', user });
await task.save();

user.tasks.push(task);
await user.save();

字符串
完整的工作示例:

// @ts-nocheck
import mongoose from 'mongoose';
import util from 'util';
import { config } from '../../config';

mongoose.set('debug', true);
console.log(mongoose.version);

const UserSchema = new mongoose.Schema({
    name: String,
    tasks: [
        {
            type: mongoose.Schema.ObjectId,
            ref: 'Task',
        },
    ],
});
const User = mongoose.model('User', UserSchema);

const TaskSchema = new mongoose.Schema({
    title: String,
    user: {
        type: mongoose.Schema.ObjectId,
        required: true,
        ref: 'User',
    },
});

const Task = mongoose.model('Task', TaskSchema);

(async function main() {
    try {
        await mongoose.connect(config.MONGODB_URI);
        // seed
        const u = new User({ name: 'Nick' });
        await u.save();

        // create task
        const user = await User.findById(u._id);
        const task = new Task({ title: 'Task 1', user });
        await task.save();
        user.tasks.push(task);
        await user.save();

        // populate
        const users = await User.find().populate('tasks');
        console.log('users:', util.inspect(users, false, null));
        const tasks = await Task.find().populate('user');
        console.log('tasks: ', util.inspect(tasks, false, null));
    } catch (error) {
        console.error(error);
    } finally {
        await mongoose.connection.close();
    }
})();


日志:

users: [
  {
    _id: new ObjectId("64afbe6276adf1531b71117c"),
    name: 'Nick',
    tasks: [
      {
        _id: new ObjectId("64afbe6376adf1531b71117f"),
        title: 'Task 1',
        user: new ObjectId("64afbe6276adf1531b71117c"),
        __v: 0
      }
    ],
    __v: 1
  }
]
Mongoose: tasks.find({}, {})
Mongoose: users.find({ _id: { '$in': [ ObjectId("64afbe6276adf1531b71117c") ], [Symbol(mongoose#trustedSymbol)]: true }}, { skip: undefined, limit: undefined, perDocumentLimit: undefined })
tasks:  [
  {
    _id: new ObjectId("64afbe6376adf1531b71117f"),
    title: 'Task 1',
    user: {
      _id: new ObjectId("64afbe6276adf1531b71117c"),
      name: 'Nick',
      tasks: [ new ObjectId("64afbe6376adf1531b71117f") ],
      __v: 1
    },
    __v: 0
  }
]

相关问题