如何将一个猫鼬模式导入到另一个?

Bab*_*abr 9 mongoose node.js

我正在制作一个节点应用程序来使用 json API,我想将User架构的各个部分分成单独的文件,因为其中有许多字段Profile并且分隔文件可以使事情更清晰:

所以基本上而不是

const userSchema = new Schema({
    username: { type: String, required: true },
    password: { type: String, required: true }, 
    profile: { 
      gender: {
       type: String,
       required: true
       },
      age: {
        type: Number
      },
      //many more profile fields come here

    }
});
Run Code Online (Sandbox Code Playgroud)

我这样做:

models/Profile.js 是:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const profileSchema = new Schema({
      gender: {
      type: String,
      required: true
      },
      age: {
        type: Number
      }
      //the rest of profile fields
});

module.exports = Profile = mongoose.model('profile', profileSchema);
Run Code Online (Sandbox Code Playgroud)

models/User.js是:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Profile = require('./Profile');

const userSchema = new Schema({
    username: { type: String, required: true },
    password: { type: String, required: true }, 
    profile: {type: Schema.Types.ObjectId, ref: 'Profile'},
});

module.exports = mongoose.model('users', userSchema);
Run Code Online (Sandbox Code Playgroud)

对于数据UserProfile张贴在同一JSON职位。

但是,当节点尝试保存对象时,我收到此错误:

(node:4176) UnhandledPromiseRejectionWarning: ValidationError: users validation failed: profile: Cast to ObjectID failed for value "{ gender: 'male'...
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

mhv*_*mhv 0

如果你创建你的模型像

module.exports = Match = mongoose.model('match', matchSchema);
Run Code Online (Sandbox Code Playgroud)

那么你必须ref使用与第一个参数相同的名称,因此不应ref: 'Match'使用 ref: match

然后,如果你想创建新文档,你应该这样做

const mongoose = require("mongoose");
const Match = require("./Match");
const User = require("./User");
...
const m = await Match.create({
    gender: "male"
});

const u = await User.create({
  username: 'user',
  password: 'password',
  match: m
});
Run Code Online (Sandbox Code Playgroud)

如果您稍后查询,例如

console.log(await User.find({}).populate("match"));
Run Code Online (Sandbox Code Playgroud)

你应该得到类似的东西

[ { _id: 5bf672dafa31b730d59cf1b4,
username: 'user',
password: 'password',
match: { _id: 5bf672dafa31b730d59cf1b3, gender: 'Male', __v: 0 },
__v: 0 } ]
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助

...

编辑

如果您从一个 JSON 获取所有数据,您仍然需要以某种方式ObjectId作为模型的参数传递User。并且它必须存在Match才能稍后填充查询。

例如

const user = req.body; // user data passed
const match = user.match;
const savedMatch = await Match.create(match);
user.match = savedMatch;
const savedUser = await User.create(user);
Run Code Online (Sandbox Code Playgroud)