Mongoose Schema - 如何创建其中一个字段是键值对数组的模式?

Mongoose Schema - How to create a schema where one of the fields is an array of key-value pairs?

 var db = require('../db');
 var post = db.Schema({
   msgtype: { type: Number },
   msgtext: { type: String },
   sender: { type: String },
   recipients: { xxxxxx },
   created_on: { type: Date }
 });
 module.exports = db.model('Post', post);

我希望收件人字段的类型为 - 数组 { 电子邮件:{类型:字符串}, 阅读:{类型:布尔值} }.

只需将 recipients 声明为数组即可:

...
recipients: [{
  email: String,
  read: Boolean
}]
...

要搜索 recipient 项,请在 email 字段中执行以下操作:

Post.findOne({'recipients.email': 'peter.w@gmail.com'}, function (err, doc) {
  if (!err) console.log(doc);
});

要更新项目,只需执行以下操作:

Post.findOneAndUpdate(
  { 'recipients.email': 'peter.w@gmail.com' },
  {
    '$set': {
      'recipients.$.read': true
    }
  },
  function(err, doc) {
});

这种方式会将 true 设置为所有 recipients,其电子邮件地址是找到的第一个文档的 peter.w@gmail.com