Node.js 和Mongoose,无法恢复_id

发布于 2024-11-27 14:48:22 字数 1859 浏览 0 评论 0原文

我正在尝试将文档保存在我的集合中,如果保存成功,则返回同一文档的 _id。问题是在这两种情况下,我的 _id 都得到一个未定义的值,无论是从猫鼬创建的模型还是从回调返回。基本上,我获取 _id 的唯一方法是通过其属性之一搜索文档,然后获取值。这种方法不是我想要的,知道我当前尝试做的事情应该有效。

var createTrophy = new Trophy({
    name            : post.name,
    accessCode      : post.password,
    description     : post.description,
    members         : [id]  
  });

  Trophy.findOne({name:post.name}, function(err, trophy) {
    if(err){
      console.log('Mongoose: Error: ' + err);
      res.send('Error db query -> ' + err);
    }
    else if(trophy){
      console.log('Trophy ' + trophy.name + ' already existant');
      res.send('Trophy ' + trophy.name + ' already existant');
    }else{  
    createTrophy.save(function(err, doc){
      var uid = createTrophy._id;
      if (err) { 
        console.log('Error in trophy saving:' + err); 
        res.send('Error in trophy saving:' + err);
      }else{ 
        User.findOne({_id:post.id}, function(err, user) {
          if(err){
            console.log('Mongoose: Error: ' + err);
            res.send('Error db query -> ' + err);
          }
          else if(user){
            console.log(doc._id + ' ' + uid);
            user.trophyLink = doc._id;
            res.send(user);
            //user.save(function(err){
            //   if(err){res.send('Couldnt update trophy of profile');} 
            //});
          }
          else{
            console.log('User id Inexistant'); 
            res.send('User id Inexistant');
          }
        });
      }
    });
    }  
  });
});

模式

 var Trophy = new Schema({
        _id             : ObjectId,
        name            : String,
        accessCode      : String,
        description     : String,
        //reference to User ID
        members         : [Number],
        comments        :[Comment]
    });

I'm trying to save a document in my collection and if the save is successful, return the _id of this same document. The problem is I get an undefined value to my _id in both case, either the created model from mongoose or from the callback return. Basically, my only way of getting the _id would be to search the document by one of its properties, and then get the value. This approach isnt what I want, knowing what im currently trying to do should work.

var createTrophy = new Trophy({
    name            : post.name,
    accessCode      : post.password,
    description     : post.description,
    members         : [id]  
  });

  Trophy.findOne({name:post.name}, function(err, trophy) {
    if(err){
      console.log('Mongoose: Error: ' + err);
      res.send('Error db query -> ' + err);
    }
    else if(trophy){
      console.log('Trophy ' + trophy.name + ' already existant');
      res.send('Trophy ' + trophy.name + ' already existant');
    }else{  
    createTrophy.save(function(err, doc){
      var uid = createTrophy._id;
      if (err) { 
        console.log('Error in trophy saving:' + err); 
        res.send('Error in trophy saving:' + err);
      }else{ 
        User.findOne({_id:post.id}, function(err, user) {
          if(err){
            console.log('Mongoose: Error: ' + err);
            res.send('Error db query -> ' + err);
          }
          else if(user){
            console.log(doc._id + ' ' + uid);
            user.trophyLink = doc._id;
            res.send(user);
            //user.save(function(err){
            //   if(err){res.send('Couldnt update trophy of profile');} 
            //});
          }
          else{
            console.log('User id Inexistant'); 
            res.send('User id Inexistant');
          }
        });
      }
    });
    }  
  });
});

The Schema

 var Trophy = new Schema({
        _id             : ObjectId,
        name            : String,
        accessCode      : String,
        description     : String,
        //reference to User ID
        members         : [Number],
        comments        :[Comment]
    });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的呼吸 2024-12-04 14:48:22

您不必在架构中提供 _id,它会自动生成。如果您希望名称是唯一的,您也可以在架构中进行配置。如果 members 应该是“真实的”用户 _ids,那么请尝试 [ObjectId] 之类的东西。

var TrophySchema = new Schema({
  name: {type:String, required:true, unique:true},
  accessCode: String,
  description: String,
  //reference to User ID
  members: [ObjectId],
  comments: [Comment]
});

我不知道这是否

var trophy = new Trophy({...data...});

像你所做的那样工作,我总是这样做:

var trophy = new Trophy();
trophy.name = "my name";
// ...

并且 _id 应该在创建对象后立即设置(http://stackoverflow.com/问题/6074245/node-mongoose-get-last-inserted-id)。

所以就这样做:

trophy.save(function (err) {
  if (err) {
    if (err.toString().indexOf('duplicate key error index') !== -1) {
      // check for duplicate name error ...
    }
    else {
      // other errors
    }
    res.send('Error in trophy saving:' + err);
  }
  else {
    User.findOne({_id:post.id}, function(err2, user) {
      if (err2) {/* ... */}
      else if (user) {
        user.trophyLink = trophy._id;
        res.send(user);
      }
    }
  }
});

重要的是,保存不会返回奖杯,你必须使用你自己创建的奖杯。

you don't have to supply _id in your Schema, it'll be generated automatically. and if you want the name to be unique you can also configure this in the Schema. if members are supposed to be "real" user _ids, than try sth like [ObjectId].

var TrophySchema = new Schema({
  name: {type:String, required:true, unique:true},
  accessCode: String,
  description: String,
  //reference to User ID
  members: [ObjectId],
  comments: [Comment]
});

and i don't know if this works

var trophy = new Trophy({...data...});

like you did it, i always do it like this:

var trophy = new Trophy();
trophy.name = "my name";
// ...

and the _id should be set as soon as you create the object (http://stackoverflow.com/questions/6074245/node-mongoose-get-last-inserted-id).

so just do it this way:

trophy.save(function (err) {
  if (err) {
    if (err.toString().indexOf('duplicate key error index') !== -1) {
      // check for duplicate name error ...
    }
    else {
      // other errors
    }
    res.send('Error in trophy saving:' + err);
  }
  else {
    User.findOne({_id:post.id}, function(err2, user) {
      if (err2) {/* ... */}
      else if (user) {
        user.trophyLink = trophy._id;
        res.send(user);
      }
    }
  }
});

important is, that save doesn't return the trophy you have to use the one you created yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文