【问题标题】:How to select document by id with Sails-mongo?如何使用 Sails-mongo 按 id 选择文档?
【发布时间】:2014-07-09 18:52:28
【问题描述】:
User.find({ _id: { '!': user.id } }, function foundFriends (err, friends) {
    if(err) return next(err);
        res.view({
            friends: friends
        });
});

MONGODB :

 {
    _id: ObjectId("53b942f7c8638f7b17670acc"),
    name: "PH",
    admin: true,
    online: false,
    encryptedPassword: "$2a$10$PjcPRgL67ZSOWDjmEwTkvu30xKeDXdCwgZ.D0.bjyDRw9sOfS/4UK",
    createdAt: ISODate("2014-07-06T12:37:11.522Z"),
    updatedAt: ISODate("2014-07-09T18:22:47.25Z")
}

此代码不起作用,我想按 ID 选择文档。我不知道我应该怎么做才能在我的风帆项目中解决这个问题。感谢您的帮助。

【问题讨论】:

    标签: javascript node.js sails.js sails-mongo


    【解决方案1】:

    我发现你的代码有一些奇怪的地方。
    1. Sails 10 的回调函数应该使用 .exec()
    2.我认为你不应该搜索_id,而应该只搜索id。我认为 waterline 会解析这个下划线。

    考虑到这一点,您的代码应该类似于

    User.find({ id: { '!': user.id } }).exec(function (err, friends) {
        if(err) return next(err);
        res.view({
            friends: friends
        });
    });
    

    【讨论】:

      【解决方案2】:

      您好,您可以通过selectselect使用sails-mongo 尝试通过id 查找、更新或销毁:

       //Schema
        module.exports = {  
         autoPK : false,
           attributes : {
             id : {
               type: 'string',
               primaryKey: true
             },
             name : {
               type : 'string'
             },
             email : {
               type : 'string'
             }
          }
       }
      
      
      
       // Find
       User.find({
         select : {id : user.id}
       }).exec((err,record)=> { 
         if(err) return console.log(err,"err");
         console.log(record,"record");
       })
      
       // Update
       User.update({
         select : {id : user.id}
       },{ 
        name : "Foo"
       }).exec((err,record)=> { 
         if(err) return console.log(err,"err");
         console.log(record,"record");
       })
      
       // Destroy
       User.destroy({
         select : {id : user.id}
       }).exec((err,record)=> { 
         if(err) return console.log(err,"err");
         console.log(record,"record");
       })
      

      希望对你有帮助。

      【讨论】:

      • mongo 为每个创建的文档指定自己的 id。因此为 id 添加一个单独的字段变得多余
      【解决方案3】:

      你可以试试这个:

      User.findOne({ _id : ObjectId(user.id.toString()) })
      

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-17
        • 2023-03-08
        • 2019-11-13
        • 2016-03-19
        • 1970-01-01
        • 1970-01-01
        • 2015-02-08
        • 2012-02-10
        相关资源
        最近更新 更多