Node.js Mongoose.js 字符串到 ObjectId 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6578178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js Mongoose.js string to ObjectId function
提问by JRPete
Is there a function to turn a string into an objectId in node using mongoose? The schema specifies that something is an ObjectId, but when it is saved from a string, mongo tells me it is still just a string. The _id of the object, for instance, is displayed as objectId("blah").
是否有使用 mongoose 将节点中的字符串转换为 objectId 的函数?模式指定某物是一个 ObjectId,但是当它从字符串中保存时,mongo 告诉我它仍然只是一个字符串。例如,对象的 _id 显示为objectId("blah")。
回答by Kevin Dente
You can do it like so:
你可以这样做:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
回答by talentedmrjones
You can do it like this:
你可以这样做:
var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");
EDIT: New standard has fromHexString rather than fromString
编辑:新标准有 fromHexString 而不是 fromString
回答by A T
Judging from the comments, you are looking for:
从评论来看,您正在寻找:
mongoose.mongo.BSONPure.ObjectID.isValid
Or
或者
mongoose.Types.ObjectId.isValid
回答by steampowered
var mongoose = require('mongoose');
var _id = mongoose.mongo.ObjectId("4eb6e7e7e9b7f4194e000001");
回答by Billy Jake O'Connor
I couldn't resolve this method (admittedly I didn't search for long)
我无法解决此方法(诚然我没有搜索很长时间)
mongoose.mongo.BSONPure.ObjectID.fromHexString
If your schema expects the property to be of type ObjectId, the conversion is implicit, at least this seems to be the case in 4.7.8.
如果您的架构期望属性为 ObjectId 类型,则转换是隐式的,至少在 4.7.8 中似乎是这种情况。
You could use something like this however, which gives a bit more flex:
但是,您可以使用类似的东西,这会提供更多的灵活性:
function toObjectId(ids) {
if (ids.constructor === Array) {
return ids.map(mongoose.Types.ObjectId);
}
return mongoose.Types.ObjectId(ids);
}
回答by Ash18
You can use this also
你也可以使用这个
const { ObjectId } = require('mongodb');
const _id = ObjectId("4eb6e7e7e9b7f4194e000001");
it's simplest way to do it
这是最简单的方法
回答by Manoj Kumar
Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)
如果您正在通过 express 和 mongoose 实现 REST API,请查看以下代码片段。(添加示例)
....
exports.AddSomething = (req,res,next) =>{
const newSomething = new SomeEntity({
_id:new mongoose.Types.ObjectId(), //its very own ID
somethingName:req.body.somethingName,
theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID
})
}
...
Hope it Helps
希望能帮助到你

