0

我想做类似以下代码的事情,但它失败了。

var User = new Schema({
    name: { type: String, required: true },
    phone_number: { type: String, required: true },
    modified: { type: Date, default: Date.now },
    contacts: [{
        user: { type : Schema.ObjectId, ref : 'User' }
    }]
});

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

它能够达到这个目的吗?

4

1 回答 1

0

我想我用了错误的方法来检查它,实际上它有效。

以下是我的测试:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('localhost', 'contacts_test');

var User = new Schema({
    name: { type: String, required: true },
    phone_number: { type: String, required: true },
    modified: { type: Date, default: Date.now },
    contacts: [
        {
            user: { type: Schema.ObjectId, ref: 'User' }
        }
    ]
});

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

mongoose.connection.on('open', function () {
    var user1 = new UserModel({name: 'kos', phone_number: "003"});

    user1.save(function (err) {
        if (err) throw err;

        var user2 = new UserModel({name: 'java', phone_number: "008"});
        user2.contacts = [{user: user1._id}];

        user2.save(function (err) {
            UserModel.findById(user2._id)
                .populate('contacts.user')
                .exec(function (err, user) {
                    if (err) console.error(err.stack || err);
                    console.log('user name: ' + user.name);
                    console.error('contact of first result : ', user.contacts[0].user.name);

                    mongoose.connection.db.dropDatabase(function () {
                        mongoose.connection.close();
                    });
                });
        });
    });
});
于 2013-08-11T11:19:18.457 回答