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

时间:2018-11-22 08:36:57

标签: node.js mongoose

我正在制作一个节点应用程序以使用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

    }
});

我这样做:

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);

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);

UserProfile的数据发布在同一json帖子中。

但是当节点尝试保存对象时,出现此错误:

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

我该如何解决?

3 个答案:

答案 0 :(得分:0)

如果您像创建模型一样

module.exports = Match = mongoose.model('match', matchSchema);

然后必须以与第一个参数相同的名称来ref,所以应使用ref: 'Match'而不是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
});

如果以后再查询,例如

console.log(await User.find({}).populate("match"));

您应该得到类似

[ { _id: 5bf672dafa31b730d59cf1b4,
username: 'user',
password: 'password',
match: { _id: 5bf672dafa31b730d59cf1b3, gender: 'Male', __v: 0 },
__v: 0 } ]

希望对您有帮助

...

编辑

如果您从一个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);

答案 1 :(得分:0)

您可以这样定义它:

/Match.js:

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

const matchSchema = new Schema({
      gender: {
      type: String,
      required: true
      },
      age: {
        type: Number
      }
});

export const mongooseMatch = mongoose.model('match', matchSchema);

/User.js:

import mongooseMatch from './Match.js';

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

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

export const matchUser = userSchema.discriminator('matchUser', mongooseMatch);

答案 2 :(得分:0)

匹配模型

// models/Match.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
      gender: {
      type: String,
      required: true
      },
      age: {
        type: Number
      }
});
module.exports = Match = mongoose.model('match', matchSchema);

用户模型

// models/User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

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

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

然后在您的请求中添加以下代码。

const User = require('../model/user');
const Match = require('../model/macth');

app.get('/test', (req, res) => {

    let newMatch = new Match({ gender: 'male'});
    newMatch.save().then(matchData => {
        console.log(matchData);
        let newUser = new User({ match: matchData._id, username: 'abc', password: '123456'});
        newUser.save().then(userData => {
            console.log(userData);
        })
        .catch(err => console.log(err));
    })
    .catch(err => console.log(err));

});

现在注销您的结果。