Mongoose Schema无法正确转换数据

时间:2016-10-13 12:42:58

标签: node.js mongodb mongoose mongoose-schema

所以,我有一个架构:

import mongoose from 'mongoose';
import cuid from 'cuid';
import timestamps from 'mongoose-timestamp';
import validators from 'mongoose-validators';

const Schema = mongoose.Schema;

const userSchema = new Schema({
  auth0id: { type: 'String', required: true },
  cuid: { type: 'String', default: cuid(), required: true },
  dateAdded: { type: 'Date', default: Date.now, required: true },
  email: { type: 'String', required: true, validate: validators.isEmail() },
  avatarURL: { type: 'String', required: true, validate: validators.isURL() },
  username: { type: 'String' },
  accessLevel: { type: 'Number', required: true },
  entities: [{ type: 'String', required: true }],
  preferredEntity: { type: 'String', required: true },
  tab_access: [{
    entityid: { type: 'String', required: true },
    tabs: [{ type: 'String' }],
  }],
  departments: [{
    entitytid: { type: 'String', required: true },
    deptid: { type: 'String', required: true },
  }],
});

userSchema.plugin(timestamps);

export default mongoose.model('User', userSchema);

我已经获得了一些我处理过的数据:

{
    email: 'client.a@thejump.tech',
    username: 'Fred Bloggs',
    accessLevel: 5,
    entities: ['cit98hg1j000578jcffur7c6h'],
    auth0id: 'auth0|57ff79140dd70f9616b80a9d',
    avatarURL: 'https://s.gravatar.com/avatar/2dfc6cb16eea798886af841e7b1ee8ab?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Ffb.png',
    preferredEntity: 'cit98hg1j000578jcffur7c6h',
    departments: [{
        entityid: 'cit98hg1j000578jcffur7c6h',
        deptid: 'cit98hg1j000572jcffur7c6h'
    }],
    tabAccess: [{
        entityid: 'cit98hg1j000578jcffur7c6h',
        tabs: []
    }]
}

当我创建新模型时:

const mongoUser = new User(userData);

......数据不一样(N.B.此时未保存):

{
    email: 'client.a@thejump.tech',
    username: 'Fred Bloggs',
    accessLevel: 5,
    auth0id: 'auth0|57ff79140dd70f9616b80a9d',
    avatarURL: 'https://s.gravatar.com/avatar/2dfc6cb16eea798886af841e7b1ee8ab?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Ffb.png',
    preferredEntity: 'cit98hg1j000578jcffur7c6h',
    _id: 57 ff791473da244be87f0489,
    departments: [{
        deptid: 'cit98hg1j000572jcffur7c6h',
        _id: 57 ff791473da244be87f048a
    }],
    tab_access: [],
    entities: ['cit98hg1j000578jcffur7c6h'],
    dateAdded: Thu Oct 13 2016 13: 07: 48 GMT + 0100(BST),
    cuid: 'ciu8aq0430000k7jck2zsi5zm'
}

它出错了:

  1. 擦除tab_access数据
  2. 从部门中删除entityid并将其替换为_id
  3. 有谁知道为什么?任何帮助都会非常感激......

    **** **** EDIT

    所以,为了清楚起见,我的路由处理程序如下所示:

    export function addUser(req, res) {
      const sentUser = req.body.user;
      console.log('sentUser', sentUser);
      const newUser = {
        connection: process.env.AUTH0_DB_CONNECTION,
        password: process.env.AUTH0_DEFAULT_PASSWORD,
        username: sentUser.username,
        nickname: sentUser.username,
        email: sentUser.email,
        email_verified: false,
        app_metadata: {
          accessLevel: sentUser.accessLevel,
        },
      };
      console.log('newUser', newUser);
      management.createUser(newUser).then(user => {
        console.log('user returned on auth0 creation: ', user);
        const storedUser = { ...req.body.user };
        console.log('storedUser pre', storedUser);
        storedUser.auth0id = user.user_id;
        storedUser.avatarURL = user.picture;
        storedUser.preferredEntity = storedUser.entities[0].entityid;
        storedUser.departments = storedUser.entities.map((ent) => {
          return {
            entityid: ent.entityid,
            deptid: ent.deptid,
          };
        });
        storedUser.tabAccess = storedUser.entities.map((ent) => {
          return {
            entityid: ent.entityid,
            tabs: [],
          };
        });
        storedUser.entities = storedUser.entities.map((ent) => {
          return ent.entityid;
        });
        console.log('storedUser post', storedUser);
        const mongoUser = new User(storedUser);
        console.log('mongoUser', mongoUser);
        mongoUser.save((err, saved) => {
          if (err) {
            console.log('problem saving', err);
            return res.status(500).send(err);
          }
          return res.status(201).send({ user: saved });
        });
      }).catch(err => {
        console.log('problem saving to Auth0')
        return res.status(500).send(err);
      });
    }
    

    其中management是auto0管理客户端。我重新排列数据以生成storedUser,然后通过在new User(storedUser)中传递数据并尝试保存模型来创建新模型。在保存模型之前,我注销了已生成的内容并查看了上述问题。

    我展示的两个对象是storedUser(帖子)和它产生的mongoUser

2 个答案:

答案 0 :(得分:0)

我有一种感觉,不必100%肯定,你必须像这样定义架构:

    function sendPostRequest()
    {
        // prepare the data that we are going to send to anymotion  
        var jsonData = querystring.stringify({
                "Land": "Land",
                "Vorname": "Vorname",
                "Name": "Name",
                "Strasse": Strasse,
            });
        var post_options = {
            host: 'achref.gassoumi.de',
            port: '443',
            method: 'POST',
            path: '/api/mAPI',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': jsonData.length
            }
        };
        // request object
            var post_req = https.request(post_options, function(res) {
            var result = '';
            res.on('data', function (chunk) {
                result += chunk;
                console.log(result);
            });
            res.on('end', function () {
            // show the result in the console : the thrown result in response of our post request
            console.log(result);
        });
        res.on('error', function (err) {
            // show possible error while receiving the result of our post request
            console.log(err);
        })
        });
        post_req.on('error', function (err) {
            // show error if the post request is not succeed
            console.log(err);
        });
        // post the data
        post_req.write(jsonData);
        post_req.end(); 
// ps : I used a https post request , you could use http if you want but you have to change the imported library and some stuffs in the code
    }

答案 1 :(得分:0)

原因是错误的密钥名称:

departments: [{
    entitytid: // change it in schema to "entityid"

注意“entitytid”的拼写。它应该是“entityid”。

其次,tab_access and tabAccess。你在模式中有tab_access,但是你在创建对象时传递了tabAccess。

在创建“storedUser”时更正此键。