简体   繁体   English

猫鼬3.8中的ObjectId数组

[英]Array of ObjectIds in Mongoose 3.8

I have a schema called Message and it has a property replies which are also Message objects. 我有一个称为Message的架构,它有一个属性replies ,它也是Message对象。 I am trying to define it in mongoose, but replies keeps returning undefined. 我试图用猫鼬来定义它,但是replies总是返回未定义的。

var MessageSchema = new Schema({
    sender: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    replies: [{type:Schema.ObjectId, ref:'Message'}],
    roomId: String,
    sendTime: Date,
    content: String,
    parentId: Schema.ObjectId
});

I've also tried replies: [MessageSchema] and replies:[Schema.ObjectId] but all of them keep returning undefined. 我也尝试了以下replies: [MessageSchema]replies:[Schema.ObjectId]但所有这些都返回未定义的内容。

Nothing wrong with the code you are listing so it's what you are not showing us that causes the problems. 您列出的代码没有错,因此导致问题的原因是您没有向我们显示。

When you reference you are going to both save a copy of the object in the collection and also add that related ObjectId value to the array of objects that are in "reply" in your case. 当您引用时,您将既要保存对象的副本到集合中,又要将该相关的ObjectId值添加到您的情况下处于“答复”状态的对象数组中。

There are several ways to do it, but a good safe MongoDB way is using $push to add additional items. 有几种方法可以做到这一点,但是一种安全的MongoDB安全方法是使用$push添加其他项。

As a complete example: 举一个完整的例子:

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


var userSchema = new Schema({
  "name": String
});

var messageSchema = new Schema({
  "sender": { "type": Schema.Types.ObjectId, "ref": "User" },
  "replies": [{ "type": Schema.Types.ObjectId, "ref": "Message" }],
  "roomId": String,
  "sendTime": { "type": Date, "default": Date.now },
  "content": String,
  "parentId": Schema.Types.ObjectId
});

var Message = mongoose.model( "Message", messageSchema );
var User = mongoose.model( "User", userSchema );

mongoose.connect('mongodb://localhost/test');

async.waterfall(
  [
    // Clean up samples
    function(callback) {
      async.each(
        [User,Message],
        function(model,callback) {
          model.remove({},callback);
        },
        callback
      )
    },

    // Create user
    function(callback) {
      User.create({ "name": "Bill" },callback);
    },

    // Create a message
    function(user,callback) {
      Message.create({
        "sender": user._id,
        "roomId": "1",
        "content": "message"
      },function(err,message) {
        callback(err,user,message);
      });
    },

    // Create a reply
    function(user,message,callback) {
      Message.create({
        "sender": user._id,
        "roomId": "1",
        "content": "reply",
        "parentId": message._id
      },callback);
    },

    // Save that reply on the parent
    function(message,callback) {
      Message.findByIdAndUpdate(
        message.parentId,
        { "$push": { "replies": message._id } },
        function(err,message) {
          console.info( message );
          callback(err);
        }
      );
    },

    // List that
    function(callback) {
      Message.find({},function(err,messages) {
        if (err) callback(err);

        console.log(
          "All:\n%s",
          JSON.stringify( messages, undefined, 4 )
        );
        callback();
      });
    }

  ],
  function(err) {
    if (err) throw err;
    mongoose.disconnect();
  }
);

And the output: 并输出:

{ _id: 54f3dff198a8c85306a2ef67,
  sender: 54f3dff198a8c85306a2ef66,
  roomId: '1',
  content: 'message',
  __v: 0,
  sendTime: Mon Mar 02 2015 14:58:41 GMT+1100 (AEDT),
  replies: [ 54f3dff198a8c85306a2ef68 ] }
All:
[
    {
        "_id": "54f3dff198a8c85306a2ef67",
        "sender": "54f3dff198a8c85306a2ef66",
        "roomId": "1",
        "content": "message",
        "__v": 0,
        "sendTime": "2015-03-02T03:58:41.387Z",
        "replies": [
            "54f3dff198a8c85306a2ef68"
        ]
    },
    {
        "_id": "54f3dff198a8c85306a2ef68",
        "sender": "54f3dff198a8c85306a2ef66",
        "roomId": "1",
        "content": "reply",
        "parentId": "54f3dff198a8c85306a2ef67",
        "__v": 0,
        "sendTime": "2015-03-02T03:58:41.393Z",
        "replies": []
    }
]

That way if you called .populate() on an message that has "replies" present, it will go back to the collection and retrieve the related data and make it appear that data was part of that item as well. 这样,如果您在显示“答复”的消息上调用.populate() ,它将返回到集合并检索相关数据,并使其看起来数据也属于该项目。

Please not that such magic does not happen "recursively" without your own intervention. 请不要在没有您自己干预的情况下不会“递归”发生这种魔术。 It's just a basic helper, so if you want more then you still have to do the lifting yourself. 它只是一个基本的帮手,因此,如果您想要更多,则仍然需要自己进行提升。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM