我正在寻找Mongo中_id的一些帮助。我想手动设置ObjectId()引用,但我不能这样做。我检查了官方mongo文档中的代码并将其插入我的应用程序但失败了。如果有人可以提供一些见解,我会非常感激。 original_id变量是我想要设置的。以下是mongo文档的链接 - https://docs.mongodb.com/manual/reference/database-references/#document-references,代码如下。任何帮助/见解都会很棒。
Template.postNewJob.events({
'submit form': function(event) {
event.preventDefault();
original_id = ObjectId();
var position = $('[name=position]').val();
var jobDescription = $('[name=jobDescription]').val();
var createdAt = new Date();
var createdBy = Meteor.userId();
postedJobs.insert({
_id: original_id,
position: position,
jobDescription: jobDescription,
createdAt: createdAt,
createdBy: createdBy
});
Router.go('dashboard');
}
});
答案 0 :(得分:0)
而不是ObjectId()
,您可能需要使用Meteor.Collection.ObjectID()
。
有关详细信息,请参阅Meteor.Collection.ObjectID() vs MongoDB ObjectId()。
答案 1 :(得分:0)
> meteor shell
Welcome to the server-side interactive shell!
Tab completion is enabled for global variables.
Type .reload to restart the server and the shell.
Type .exit to disconnect from the server and leave the shell.
Type .help for additional help.
> Coll = new Mongo.Collection('coll')
默认插入,Meteor将生成_id
> Coll.insert({str: "blah"})
'JTeBKdTErXWQyedMN'
将传递的ObjectID对象作为_id
插入> Coll.insert({_id: new Meteor.Collection.ObjectID(), str: "blah"})
{ [String: '8dbfd702d76d6152685e2f66'] _str: '8dbfd702d76d6152685e2f66' }
使用用户构造的String作为_id
插入> Coll.insert({_id: "1234", str: "blah"})
'1234'
当然,如果您创建自己的_id值,则您有责任确保集合中尚未存在_ids,否则您的插入内容将被拒绝:
> Coll.insert({_id: "1234", str: "blah"})
WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error index: meteor.coll.$_id_ dup key: { : \"1234\" }","op":{"_id":"1234","str":"blah"}})
... more stack trace follows
然后你的收藏品如下:
> Coll.find({}).fetch()
[ { _id: 'JTeBKdTErXWQyedMN', str: 'blah' },
{ _id: { [String: '8dbfd702d76d6152685e2f66'] _str: '8dbfd702d76d6152685e2f66' },
str: 'blah' },
{ _id: '1234', str: 'blah' } ]
> Coll.findOne('JTeBKdTErXWQyedMN')
{ _id: 'JTeBKdTErXWQyedMN', str: 'blah' }
> Coll.findOne('1234')
{ _id: '1234', str: 'blah' }
> Coll.findOne(new Meteor.Collection.ObjectID('8dbfd702d76d6152685e2f66'))
{ _id: { [String: '8dbfd702d76d6152685e2f66'] _str: 8dbfd702d76d6152685e2f66' }, str: 'blah' }
答案 2 :(得分:0)
我能够弄清楚。我需要按以下方式设置它: var original_id = new Meteor.Collection.ObjectID()。valueOf();