如何在具有填充字段的集合中创建新对象

时间:2019-05-09 17:51:26

标签: javascript node.js mongodb express mongoose

我目前正在参加一个学校项目。我必须创建一个网站,并且想做一个MEAN应用程序。一切都很好,直到我想为猫鼬设计好的模型。我将在一个集合中包含用户(名称,psswd等),而我的“详细信息”将在另一个集合中。

我知道如何查询,查找和组合数据。全部在猫鼬文档中,但是...

我不知道如何使用专用的“详细信息”来创建新用户(在回答POST请求时)。

什么是填充方法?

~User.cardid.create()~ ?
~
var cardIDSchema = new mongoose.Schema({
  userID: String,
  name: String,
  surname: String,
  date_Of_Birth: Date,
  address: String,

var userSchema = new mongoose.Schema({
  email: String,
  psswd: String,
  cardID: { type: mongoose.Schema.Types.ObjectId, ref: 'CardID'}
});~

1 个答案:

答案 0 :(得分:0)

如果您来自 SQL 世界,则populate方法的工作原理类似于join语句,在该语句中,它使用一个表中的引用列来获取相应的项用于外部表。在上面的模式中,如果要获取使用并希望检索随附的detailed information,则可以像这样populate那样使用User.findOne().populate('cardId');方法

为了方便起见,我已经修改了以下架构。

使用此架构创建具有相应详细信息的新用户:

var cardIDSchema = new mongoose.Schema({
  name: String,
  surname: String,
  date_Of_Birth: Date,
  address: String,
})

var Card = mongoose.model('Card', cardIDSchema);

var userSchema = new mongoose.Schema({
  email: String,
  psswd: String,
  cardID: { type: mongoose.Schema.Types.ObjectId, ref: 'CardID'}
});

const User = mongoose.model('user', userSchema);

您必须先创建卡信息才能获得ObjectId,然后用户才能跟踪。


//...
// Create the card first.
var card = new Card({
  name: 'Some',
  surname: 'Person',
  date_Of_Birth: Date.now(),
  address: 'Somewhere in the world'
}); // this will create a new card._id automatically

// Create the user and pass the card._id as the reference.
var user = new User({
  email: 'test@example.org',
  psswd: 'somesecret',
  cardID: card._id
});

/**
 * Depending on if you're using an async/await function...
 */
// For async...
// Save the card information first.
await card.save();

// Then save the user information.
await user.save();


// For callbacks...
card.save(function (err) {
    if (err) ; // Do something with error.

    user.save(function (err) {
        if (err) ; // Do something with the error.
});

//...

检索模型甚至更加容易,这就是创建populate方法的原因。


//...

// Say the id of the user you created was '5cd47029324acd59fc666df6'
// Using the async/await function...
var user = await User.findById('5cd47029324acd59fc666df6').populate('cardID');

// Using callback...
User.findById('5cd47029324acd59fc666df6')
    .populate('cardID')
    .exec(function (err, user) {
        if (err) ; // Do something with error.

        // Continue with user here...
    });

// The user variable will then be...
/**
 * {
 *    _id: '5cd47029324acd59fc666df6',
 *    email: 'test@example.org',
 *    psswd: 'somesecret',
 *    cardID: {
 *        _id: '5cd47652324acd59fc666df7',
 *        name: 'Some',
 *        surname: 'Person',
 *        date_Of_Birth: Date.now(),
 *        address: 'Somewhere in the world'
 *    }
 * }
 */

//...

PS :为确保一致性,请使用fawn npm模块,该模块模仿一种事务状态,以确保在继续之前保存所有数据,并且如果其中一个模型不是保存,将从数据库中删除最初保存的模型。

相关问题