Probably something very simple here. I have 2 mongoDb collections, one (users) with an objectId and the other (listings) which has the userId.
I want to get the documents in the listing collection by searching the objectId (currentUser._id).
How would i do this?
Component for page i want to display the listings on:
export class ManageComponent implements OnInit {
listing : Listing;
listings: Listing[] = [];
currentUser: User;
constructor(
private listingService: ListingService,
private userService: UserService) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
ngOnInit() {
this.loadAllListings();
}
private loadAllListings() {
this.listingService.getAll().subscribe(listings => { this.listings = listings; });
}
private loadById(userId: string) {
this.listingService.getById(userId).subscribe(listings => { this.listings = listings});
}
}
I have a listing service that is used to for the CRUD operations (some omitted)
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Listing } from '../_models/index';
@Injectable()
export class ListingService {
constructor(private http: Http) { }
getAll() {
return this.http.get('/listings').map((response: Response) => response.json());
}
getById(_id: string) {
return this.http.get('/listings/' + _id).map((response: Response) => response.json());
}
getByUserId(userId: string) {
return this.http.get('/listings/' + userId).map((response: Response) => response.json());
}
create(listing: Listing) {
return this.http.post('/listings/add', listing);
}
Server side listing controller which uses the server side service (see below):
function getRelevant(req, res) {
listingService.getByUserId(req.listing.sub)
.then(function (listing) {
if (listing) {
res.send(listing);
} else {
res.sendStatus(404);
}
})
.catch(function (err) {
res.status(400).send(err);
});
}
Server side listing service:
function getByUserId(userId) {
var deferred = Q.defer();
db.listings.findById(userId, function (err, listing) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (listing) {
// return listing
deferred.resolve(listing);
} else {
// listing not found
deferred.resolve();
}
});
return deferred.promise;
}
db.listings.aggregate([$ lookup:{from:“ users”,localField:“ currentUser._id”,foreignField:“ _id”,as:“ result”}}]))。findOne({搜索})
MongoDB's function findById()
will find the current model's documents by Id on which the function is operated ( db.listings.findById()
will find All Listings by Listing Id).
That said, if you want to find
by other criteria that is in your model ( listing
). You need to do find({query})
.
Specifically in your case, you'll need to:
const query = {userId: userIdThatIsPassedIn};
db.listings.find(query).exec(callback);
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.