【问题标题】:How to create a new object in a collection that have a populate field如何在具有填充字段的集合中创建新对象
【发布时间】:2019-05-10 02:57:08
【问题描述】:

我目前正在做一个学校项目。我必须创建一个网站,我想做一个 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'}
});~

【问题讨论】:

  • 除非您有某种一对多关系,否则您应该将所有内容存储在一起。
  • 是的,我就是这么想的,我只是想玩
  • 当您实例化您的模型时,您是否将其名称/引用设置为“CarID”,例如。 mongoose.model("CardID", CardIDSchema) ??
  • 是的,我正在这样做,而且对用户也是如此

标签: javascript node.js mongodb express mongoose


【解决方案1】:

如果您来自 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'
 *    }
 * }
 */

//...

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

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多