Grails可以通过ID 轻松获取域对象(方便构建REST API).
用于检索资源的控制器可以如下所示:
MetricController.groovy
import grails.converters.JSON
class MetricController {
def index() {
def resource = Metric.get(params.id)
render resource as JSON
}
}
Run Code Online (Sandbox Code Playgroud)
使用MongoDB GORM(compile ":mongodb:1.2.0")的Grails插件时id,Long 需要将默认类型更改为type String或ObjectId.
Metric.groovy
import org.bson.types.ObjectId
class Metric {
static mapWith = "mongo"
ObjectId id
String title
}
Run Code Online (Sandbox Code Playgroud)
但是,做一个.get(1)遗嘱现在会导致:
Error 500: Internal Server Error
URI
/bow/rest/metric/1
Class
java.lang.IllegalArgumentException
Message
invalid ObjectId [1]
Run Code Online (Sandbox Code Playgroud)
我猜了一下并改变了控制器使用findById:
def resource = Metric.findById(new ObjectId(new …Run Code Online (Sandbox Code Playgroud) 我的网址目前看起来像这样:
http://www.sitename.com/watch?companyId=507f1f77bcf86cd799439011&employeeId=507f191e810c19729de860ea&someOtherId=.....
Run Code Online (Sandbox Code Playgroud)
所以,正如你所看到的,它变得非常长,非常快.我在考虑缩短这些ObjectIds.想法是我应该为我的数据库中的每个模型添加名为"shortId"的新字段.所以不要:
var CompanySchema = mongoose.Schema({
/* _id will be added automatically by mongoose */
name: {type: String},
address: {type: String},
directorName: {type: String}
});
Run Code Online (Sandbox Code Playgroud)
我们会这样:
var CompanySchema = mongoose.Schema({
/* _id will be added automatically by mongoose */
shortId: {type: String}, /* WE SHOULD ADD THIS */
name: {type: String},
address: {type: String},
directorName: {type: String},
});
Run Code Online (Sandbox Code Playgroud)
我找到了这样做的方法:
// Encode
var b64 = new Buffer('47cc67093475061e3d95369d', 'hex')
.toString('base64')
.replace('+','-')
.replace('/','_')
;
// -> shortID is now: R8xnCTR1Bh49lTad
Run Code Online (Sandbox Code Playgroud)
但我仍然认为它可能更短.
另外,我发现这个npm模块: …
我想查询 MongoDB 数据库中的集合以查找包含部分 ObjectID 的所有记录。对于普通字符串,我可以使用如下正则表达式:
db.teams.find({"some_string": /^51eed/})
Run Code Online (Sandbox Code Playgroud)
但是我该如何对 ObjectID 执行类似的操作呢?
具体来说,我有一个看起来像这样的集合:
{ "status" : 0, "_id" : ObjectId("51e97ff613e737801d000002") }
{ "status" : 0, "_id" : ObjectId("51ee7513d1f7c57420000002") }
{ "status" : 0, "_id" : ObjectId("51eed9dd5b605af404000002") }
{ "status" : 0, "_id" : ObjectId("51eedab39108d8101c000002") }
Run Code Online (Sandbox Code Playgroud)
我想查询(在 mongo 中)ObjectId 以“51eed”开头的所有记录。非常感谢您的帮助。
我不知道我做错了什么.
我使用Sailsv0.10和mongo2.6.0并希望通过native更新集合中的数组字段(使用$ push).
我的模特:
module.exports = {
schema: true,
attributes: {
username: {
type: 'string',
required: true
},
pubs: {
type: 'array',
defaultsTo: []
},
...
Run Code Online (Sandbox Code Playgroud)
我的功能:
User.native(function (err, collection) {
collection.update({username:aUsernameVariable},{$push:{pubs:aPubsVariable}}, function (err) {
});
Run Code Online (Sandbox Code Playgroud)
它到目前为止工作.但是为什么这不能用作id字段的查询?
User.native(function (err, collection) {
collection.update({id:anIdVariable},{$push:{pubs:aPubsVariable}}, function (err) {
});
Run Code Online (Sandbox Code Playgroud)
我肯定使用正确的id来查询它.
我究竟做错了什么?或者是Sails-Mongo适配器的ObjectId类型转换问题
我在MongoDB中有两个集合,一个是用户,另一个是动作.用户看起来大致如下:
{_id: ObjectId("xxxxx"), country: "UK",...}
Run Code Online (Sandbox Code Playgroud)
和行动一样
{_id: ObjectId("yyyyy"), createdAt: ISODate(), user: ObjectId("xxxxx"),...}
Run Code Online (Sandbox Code Playgroud)
我试图计算按国家/地区划分的事件和不同用户.上半部分工作正常,但是当我尝试添加一个子查询来拉动国家时,我只能获得国家/地区的空值
db.events.aggregate({
$match: {
createdAt: { $gte: ISODate("2013-01-01T00:00:00Z") },
user: { $exists: true }
}
},
{
$group: {
_id: {
year: { $year: "$createdAt" },
user_obj: "$user"
},
count: { $sum: 1 }
}
},
{
$group: {
_id: {
year: "$_id.year",
country: db.users.findOne({
_id: { $eq: "$_id.user_obj" },
country: { $exists: true }
}).country
},
total: { $sum: "$count" },
distinct: { $sum: 1 }
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试将多个用户批量插入数据库.出于测试目的,我想为每个单独的文档设置一个特定的ObjectId.由于某种原因,我无法插入有效的ObjectId.
例如:
var users = [
{
"_id": "56955ca46063c5600627f393",
"name": "John"
},
{
"_id": "56955ca46063c5600627f392",
"name": "Doe"
}
];
User.collection.insert(users, function(err, docs) {
if (err) {
console.log("Error");
} else {
console.log("Succes")
}
});
Run Code Online (Sandbox Code Playgroud)
...插入mongoDB:
"_id" : "56955ca46063c5600627f393" //NOT ObjectId("56955ca46063c5600627f393")
Run Code Online (Sandbox Code Playgroud)
当我尝试查询具有指定_id的文档时,这会导致各种问题.我的原始代码工作正常但缺少漂亮的多插入选项:
var user1 = new User({
"_id": "56955ca46063c5600627f393",
"name": "John"
});
var user2 = new User({
"_id": "56955ca46063c5600627f392",
"name": "Doe"
});
user1.save(function(err, response){
user2.save(function(err, response){
if (err) console.log(err);
else console.log("ok");
done();
})
});
Run Code Online (Sandbox Code Playgroud)
在mongoDB中插入:
ObjectId("56955ca46063c5600627f393")
Run Code Online (Sandbox Code Playgroud)
有没有办法使用有效的ObjectId在数据库中插入多个文档?
怎么样/我可以得到
3字节计数器,以随机值开始
部分来自mongodb ObjectId?
我有一个像这样的ObjectId:ObjectId("507f1f77bcf86cd799439011")
根据mongodb文档:
描述
ObjectId()返回一个新的ObjectId值.12字节的ObjectId值包括:
一个4字节的值,表示自Unix纪元以来的秒数,
一个3字节的机器标识符,
一个2字节的进程ID,
和一个3字节的计数器,以随机值开始.
我希望得到" 和一个3字节计数器,从一个随机值开始. "如果可能的话,从上面的ObjectId开始.
我尝试通过查找特定的“_id”来查询我的 MongoDB,但新的 ObjectID 不能解决问题。我尝试通过“var obj = new ObjectID()”创建一个包含随机 ObjectID 的变量,但它不起作用。然后我检查我的 MongoDB 版本,它是最新的(db 版本 v4.0.2)。服务器连接工作正常。有什么想法吗?谢谢。
我的收藏:
[
{
"_id": "5bc9fe6683dfb93706fe8a24",
"name": "Luis",
"occupation": "Doctor"
},
{
"_id": "5bc9fe6683dfb93706fe8a25",
"name": "Peter",
"occupation": "Student"
}
]
Run Code Online (Sandbox Code Playgroud)
芒果代码:
const {MongoClient} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017/NewApp',(err, client) => {
if(err){
return console.log("Unable to connect to MongoDB server");
}
console.log("Connect to MongoDB server");
const db = client.db('NewApp');
db.collection('Users').find({"_id": new ObjectID("5bc9fe6683dfb93706fe8a24")}).toArray().then((data) => {
console.log(JSON.stringify(data, undefined, 2));
},(error) => {
if(error){console.log("Unable to fetch the data", error)}
});
client.close();
});
Run Code Online (Sandbox Code Playgroud)
错误: …
将MongoDB ObjectID键入52489e882967060200000283Google电子表格中的单元格,并将其破坏?.是什么赋予了?
objectid ×10
mongodb ×9
node.js ×4
javascript ×2
mongoose ×2
grails ×1
grails-orm ×1
join ×1
rest ×1
sails.js ×1