问题
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")
}
This Code doesn't work, I would like to select document by Id. I don't know what I should do to fix that in my sails project. Thank you for your help.
回答1:
There are couple of things I see are weird with your code.
1. The callback function as for sails 10 should be executed with .exec()
2. I think you should not search for _id
but only id
. I think waterline parses this underscore.
Having that in mind your code should look something like
User.find({ id: { '!': user.id } }).exec(function (err, friends) {
if(err) return next(err);
res.view({
friends: friends
});
});
回答2:
Hi you can try this for find, update, or destroy by id with sails-mongo via select
:
//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");
})
Hope this can help to you.
回答3:
You can try this:
User.findOne({ _id : ObjectId(user.id.toString()) })
Hope this help.
来源:https://stackoverflow.com/questions/24661635/how-to-select-document-by-id-with-sails-mongo