簡體   English   中英

在MongoDB中存儲和返回ObjectId(MEAN堆棧)

[英]Storing and Returning an ObjectId in MongoDB (MEAN Stack)

我是MEAN堆棧的新手,如何使用JavaScript從MongoDB正確鏈接ObjectId遇到了麻煩。 我還試圖獲取與該ObjectId對應的名稱以在我的視圖中顯示。

該代碼用於按時間表進行約會,其中用戶與每個約會相關聯,然后視圖顯示有關每個約會的信息(即每個用戶的姓名)。

這是我的計划模式:

'use strict';

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

var ScheduleSchema = new Schema({
  description: String,
  category: [String],
  location: String,
  startDate: { type: Date, default: Date.now },
  endDate: { type: Date, default: Date.now },
  participants: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }],
  author: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  timestamp: { type: Date, default: Date.now },
  active: Boolean
});

module.exports = mongoose.model('Schedule', ScheduleSchema);

以及用戶的架構:

var UserSchema = new Schema({
  name: String,
  email: { type: String, lowercase: true },
  role: {
    type: String,
    default: 'user'
  },
  hashedPassword: String,
  provider: String,
  salt: String
});

^文件還有很多,但我認為架構是唯一相關的部分。

這是我的控制器代碼,該代碼通過帶有2個真實用戶objectid(參與者)的虛假測試信息進行傳遞:

// Use our rest api to post a new meeting
$scope.addMeeting = function() {
  $http.post('/api/schedules', { description: "Testing schedule adding", participants: ["547f03befccbd4f93874b547", "5481dcbf5dad7f735a766ad9"], category: "1", location: "Small Conference Room", startDate: new Date(), endDate: new Date(), timestamp: new Date(), active: true });
};

我已經發布了,但是當我從日程表中獲取所有約會並將它們放在視圖中時,(也許很明顯)顯示的是ObjectId而不是名稱,因此:

<table style="width:100%;">
  <tr>
    <td class="left" ng-class="'head'">Time</td>
    <td ng-class="'head'">Attendees</td>
    <td ng-class="'head'">Description</td>
    <td class="right" ng-class="'head'">Location</td>
  </tr>
    <tr ng-repeat="meeting in meetings">
      <td class="left" ng-class-even="'even'">{{ meeting.startDate | date:"h:mma" }} - {{ meeting.endDate | date:"h:mma" }}</td>
      <td ng-class-even="'even'"><span ng-repeat="person in meeting.participants">{{ person }}<span ng-hide="$last">, </span></span></td>
      <td ng-class-even="'even'">{{ meeting.description }}</td>
      <td class="right" ng-class-even="'even'">{{ meeting.location }}</td>
    </tr>
</table>

變成這樣:(我發布了一張圖片,但是信譽點不夠,所以顯示的所有圖片都是“參與者”列下方的“用戶的對象ID”,而不是名稱)

而且我想知道您應該如何正確鏈接事物以便能夠顯示名稱而不是那些ObjectId。

對不起這本小說,希望我能講清楚。

在使用貓鼬時,請使用populate來加載關系。 在MongoDB中,您將user._id存儲在schedule.participants ,因此,當您列出日程表或查詢確切的Schedule時,請確保您填充schedule.participants數組。

http://mongoosejs.com/docs/populate.html

Schedule
.findOne({ title: 'Once upon a timex.' })
.populate('participants')
.exec(function (err, story) {
if (err) return handleError(err);
  console.log('The creator is %s', story._creator.name);
  // prints "The creator is Aaron"
})

角度代碼也應根據需要綁定到用戶的名稱或電子郵件。 {{ person.name }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM