简体   繁体   中英

How to find by _Id in mongoDB with node.js

I need to find in my DB with _id .it works with others like 'name...' but with _id, I get a syntax error. For example, this is my DB.find input.

{ "_id": ObjectID("584820a96866b6283361a4b9")}

I get a syntax error: ObjectId is not defined. I also tried these codes:

{ "_id": 'ObjectID("584820a96866b6283361a4b9")'}
{ "_id": '584820a96866b6283361a4b9'}
{ "_id": 584820a96866b6283361a4b9}

But none of them working.

What's my problem?

If you are using mongoose

// Using Node.js `require()`
const mongoose = require('mongoose');

// Using ES6 imports
import mongoose from 'mongoose';

find({_id: mongoose.Types.ObjectId("584820a96866b6283361a4b9")})

If you are using mongoDB

// Using Node.js `require()`
const { ObjectId } = require('mongodb');
// or var ObjectId = require('mongodb').ObjectId if node version < 6 

// Using ES6 imports
import { ObjectId} from 'mongodb';

find({_id: ObjectId("584820a96866b6283361a4b9")})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM