通过Mongoose将嵌套对象结果从MongoDB获取到节点环境的麻烦

时间:2018-08-06 13:22:53

标签: node.js mongodb mongoose-schema

在这里,我试图将有关上述架构和数据的一些数据存储到MongoDB。而且我还可以使用代码存储确切的数据。但是在尝试获取时,我无法获得用户的名称,因为它位于结果对象内的对象中。

架构

var mongoose = require('mongoose');
var sch = mongoose.Schema;

var userSchema = new sch({
userid: Number,
name: {
    first: {
        type: String, 
        required: true
    },
    last: String
},
age: Number,
linkedin: {
    type: String,
    validate: {
        validator: function(text) {
            return text.indexOf('https://www.linkedin.com/') === 0;
        },
        message: 'LinkedIn must start with https://www.linkedin.com/'
    }
},
description: String
});

var User = mongoose.model('User', userSchema);

module.exports = User;

示例数据

var Data = new User({
    userid: Math.floor(Math.random()*1000),
    name: {
        first: "foo",
        last: "bar"
      },
    age: 30,
    description: 'Backend Developer',
    linkedin: 'https://www.linkedin.com/End-Your-If-194251957252562/')};

将数据存储到mongo数据库

    mongoose.connect('mongodb://localhost/mongo', function (err) {
        if (err) throw err;

        console.log('Successfully connected');

        var User = **Data**;
    // Data is above mentioned hard coded one.

        User.save(function(err) {
            if (err) throw err;
            console.log('User successfully saved.'); 
        });

    });
    mongoose.model('users', {name: String});

MongoDB存储的数据

    { "_id" : ObjectId("5b683e4b05c56f4e08662017"), "name" : { "first" : "foo", "last" : "bar" }, "userid" : 718, "age" : 30, "description" : "Backend Developer", "linkedin" : "https://www.linkedin.com/End-Your-If-194251957252562/", "__v" : 0 }

代码,用于尝试通过猫鼬从mongo数据库中获取保存的数据

    app.get('/users', function(req, res) {
        mongoose.model('users').find(function(err, users) {
            if (err) throw err;
            console.log(JSON.stringify(users));
            res.send(users);
        })
    });

通过猫鼬得到的结果未显示用户名

    [{"_id":"5b683e4b05c56f4e08662017","userid":718,"age":30,"description":"Backend Developer","linkedin":"https://www.linkedin.com/End-Your-If-194251957252562/","__v":0}

任何人,请帮助我解决此问题

谢谢, 拉瓦尼亚

1 个答案:

答案 0 :(得分:0)

该行下面的内容使您的数据混乱。

mongoose.model('users', {name: String});

请删除此内容。