首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在mongoDB对象中添加唯一的自动增量ID

如何在mongoDB对象中添加唯一的自动增量ID
EN

Stack Overflow用户
提问于 2016-11-01 07:05:48
回答 1查看 197关注 0票数 0

我有桌位使用者。这是模式。

代码语言:javascript
运行
复制
var usersSchema = mongoose.Schema({
  uname : {type : String , unique: true},
  email : {type : String},
  logintype : {type : String},
  password : String,
  status : String,
  hash : String,
  social: {},
  games: Object,
  os: String,
  friends: Object,
  msges:Object
});

味觉是物体。但是我想要的是在msges中有键值对。所以我做的是

代码语言:javascript
运行
复制
function sendMsgToFriend(uname,friendUname,title,msg,time,callback){
  global.users.find({"uname":friendUname},
    function(err,doc){
        if(err){
          callback(false,err,"Msg cannot be sent");
        }else{
          global.users.update( {"uname" : uname},
            {
              $addToSet : {
                "msges":{time:{"from":uname,"title":title,"msg":msg,"read":false}}
              }
            },function(err,doc){
              if(err){
                  callback(false,err,"Msg cannot be sent");
              }else{
                  callback(true,null,"Msg has been sent");
              }
            }
          );
        }
    }
  );
}

我试着让“时间”成为关键,让它的价值得到休息。但所发生的是,不是时间的价值,字符串“时间”出现了。我能用msges做一个自动递增键吗?提前谢谢你。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-01 07:47:43

你将"msgs“定义为一个对象,但我从您的问题中看到的是,您需要一组对象。

为什么不为消息创建一个模型,并使"msgs“成为对该对象的引用数组。

代码语言:javascript
运行
复制
var usersSchema = mongoose.Schema({
  uname : {type : String , unique: true},
  email : {type : String},
  logintype : {type : String},
  password : String,
  status : String,
  hash : String,
  social: {},
  games: Object,
  os: String,
  friends: Object,
  msges: [{
      message_id : { type: Schema.Types.ObjectId, ref: 'Message' },
      read_on : Boolean }]
});

和消息的架构。

代码语言:javascript
运行
复制
var messageSchema = Schema({
  from : String,
  title: String,
  msg : String,
  send_on : Date
});

var Message  = mongoose.model('Message', messageSchema);

这样,所有消息都在一个集合中,您可以跟踪每个用户的读取状态。

要在用户检索期间检索消息,可以使用猫鼬种群

UPDATE:如果您不想要xtra集合,请让您的用户模式类似于:

代码语言:javascript
运行
复制
var usersSchema = mongoose.Schema({
      uname : {type : String , unique: true},
      email : {type : String},
      logintype : {type : String},
      password : String,
      status : String,
      hash : String,
      social: {},
      games: Object,
      os: String,
      friends: Object,
      msges: [{
          id : Schema.Types.ObjectId,
          from : String,
          title: String,
          msg : String,
          send_on : Date,
          read_on : Boolean }]
    });

但是请记住,如果您也希望消息与发送消息的用户在一起,则需要将消息放在两个用户的数组中(保持id相等).因此,您应该考虑/讨论场景中最好的解决方案。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40355480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档